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?

4 Comments »

  1. 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));

  2. 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

  3. Felipe Delgado said,

    October 12, 2010 at 7:29 pm

    I tried to make work the array like you have, and I can’t; instead of, I made an array of JSON objects, like this:

    var maxSpeed = [
    {vehicle:'car', velocity:300},
    {vehicle:'bike',velocity:60},
    {vehicle:'motorbike',velocity:200},
    {vehicle:'airplane', velocity:1000},
    {vehicle:'helicopter',velocity:400},
    {vehicle:'rocket', velocity:8*60*60}
    ];

    then, I used a sorting function that sort the array using the velocity property of the objects.

    function SortByVelocity(a,b)
    { return a.velocity - b.velocity; }

    maxSpeed.sort(SortByVelocity);

    and it’s works very fine!

  4. Naveen said,

    April 4, 2011 at 8:13 am

    I am also searching for similar kind of sorting. Kindly give me an idea how do we implement this in a class using a private method.

RSS feed for comments on this post · TrackBack URL

Leave a Comment