JavaScript: Sort object by a value
Actually the headline is not really what I want to say :-). But I don’t know any better yet.
I just want to write down how I solved sorting the following:
>>> var maxSpeed = {car:300, bike:60, motorbike:200, airplane:1000,
helicopter:400, rocket:8*60*60}
This is a list of vehicles with their (approx.) max speeds. And now, I would like a list of the vehicles sorted by their max speed. This looks sooo easy, and actually it is :-). You just have to know how.
Look at this:
>>> 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]]
Since the sort function takes an extra argument, that allows to do your custom comparison we simply make sure that the right stuff gets compared, which is our speed. Unfortunately we can not sort the object directly, it has to be an array for doing so. But you can now convert it back, or just extract the vehicles, like so:
>>> dojo.require("dojox.lang.functional")
>>> vehiclesSortedBySpeed =
dojox.lang.functional.map(sortable, function(i) {return i[0]})
["bike", "motorbike", "car", "helicopter", "airplane", "rocket"]
Didn’t I say it was easy?
peter higgins said,
May 20, 2008 at 7:38 pm
function sortObj(theObj, idx){
var sortable = [];
for(var i in theObj){
sortable.push([i, theObj[i]]);
}
sortable.sort(function(a,b){
return a[idx] - b[idx];
});
return dojo.map(sortable,function(elm){ return elm[0]; });
}
var obj = {
car: 300, bike:60, motorbike:200, airplane:1000,
helicopter: 500, rocket: 8*60*60
};
console.log(sortObj(obj,1));
Thomas Frank said,
May 27, 2008 at 12:58 am
I wrote a sorter for arrays of objects a while ago that also comes to mind:
http://www.thomasfrank.se/sorting_things.html