Sorting JavaScript Object by property value

Sorting JavaScript Object by property value

>>>var maxSpeed ={car:300, bike:60, motorbike:200, airplane:1000,
    helicopter:400, rocket:8*60*60}
>>>var sortable =[];
>>>for(var vehicle in maxSpeed)
      sortable.push([vehicle, maxSpeed[vehicle]])
>>> sortable.sort(function(a, b){return a[1]- b[1]})
[["bike",60],["motorbike",200],["car",300],
["helicopter",400],["airplane",1000],["rocket",28800]]
function sortObject(obj){
    var arr =[];
    for(var prop in obj){
        if(obj.hasOwnProperty(prop)){
            arr.push({
                'key': prop,
                'value': obj[prop]
            });
        }
    }
    arr.sort(function(a, b){return a.value - b.value;});
    return arr;// returns array
}

var list ={"you":100,"me":75,"foo":116,"bar":15};
var arr = sortObject(list);
console.log(arr);
var names =[{name:'Will'},{name:'Bill'},{name:'Ben'}];
names.sort(function(a, b){
    return(a.name.localeCompare(b.name));
});
console.log(names);

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s