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?
