12

In javascript, is there an easy way to sort key-value pairs by the value (assume the value is numeric), and return the key? A jQuery way to do this would be useful as well.

(There are a lot of related questions about key-value pairs here, but I can't find one specifically about sorting.)

5 Answers 5

21

There's nothing easy to do this cross-browser. Assuming an array such as

var a = [
    {key: "foo", value: 10},
    {key: "bar", value: 1},
    {key: "baz", value: 5}
];

... you can get an array of the key properties sorted by value as follows:

var sorted = a.slice(0).sort(function(a, b) {
   return a.value - b.value;
});

var keys = [];
for (var i = 0, len = sorted.length; i < len; ++i) {
    keys[i] = sorted[i].key;
}

// keys is ["bar", "baz", "foo"];
1
  • 2
    This was not the only good answer but this one came closest to doing what I wanted in a way I could understand. That's not to say it's the best answer. Commented Feb 12, 2011 at 6:36
7

Let's assume we have an Array of Objects, like:

var data = [
    {foo: 6},
    {foo: 2},
    {foo: 13},
    {foo: 8}
];

We can call Array.prototype.sort()help, use Array.prototype.map()help to map a new array and Object.keys()help to grab the key:

var keys = data.sort(function(a,b) {
    return a.foo - b.foo;
}).map(function(elem, index, arr) {
   return Object.keys(elem)[0];
});

Be aware of, Array.prototype.map() requires Javascript 1.6 and Object.keys() is ECMAscript5 (requires Javascript 1.8.5).

You'll find alternative code for all those methods on MDC.

1
  • Thank you for this. When I tried running it, it didn't like "Object.keys(elem)[0]"...I'll try to recreate the error later. What is the "Object" doing in there? Forgive me if it's a silly question. Commented Feb 12, 2011 at 6:31
4

As far as I know, there isn't a built-in Javascript function to sort an array by its keys.

However, it shouldn't take too much code to do it: just extract the keys into their own array, sort them using the normal sort function, and rebuild the array in the right order. Something like this should do the trick:

function SortArrayByKeys(inputarray) {
  var arraykeys=[];
  for(var k in inputarray) {arraykeys.push(k);}
  arraykeys.sort();

  var outputarray=[];
  for(var i=0; i<arraykeys.length; i++) {
      outputarray[arraykeys[i]]=inputarray[arraykeys[i]];
  }
  return outputarray;
}

Now you can just call your function like so:

var myarray = {'eee':12, 'blah':34 'what'=>66, 'spoon':11, 'snarglies':22};
myarray = SortArrayByKeys(myarray);

And the output will be:

{'blah':34, 'eee':12, 'spoon':11, 'snarglies':22, 'what':66}

Hope that helps.

Working test page here: http://jsfiddle.net/6Ev3S/

2
  • Thanks, but I want to sort by the values, and return the key. Commented Feb 11, 2011 at 13:50
  • @David Rhoden - oh, right.... then you can just use array.sort(), followed by for(var key in array) {...}.
    – Spudley
    Commented Feb 11, 2011 at 14:19
4

Given

var object = {
  'a': 5,
  'b': 11,
  'c': 1,
  'd': 2,
  'e': 6
}

You can sort object's keys by their values using the following:

Object.keys(object).sort(function (a, b) {
  return object[a] - object[b]
}))

Result

[ 'c', 'd', 'a', 'e', 'b' ]
1

If you can't count on the exended array and object properties,

you can use the original Array methods-

function keysbyValue(O){
    var A= [];
    for(var p in O){
        if(O.hasOwnProperty(p)) A.push([p, O[p]]);
    }
    A.sort(function(a, b){
        var a1= a[1], b1= b[1];
        return a1-b1;
    });
    for(var i= 0, L= A.length; i<L; i++){
        A[i]= A[i][0];
    }
    return A;
}
//test

    var Obj={a: 20, b: 2, c: 100, d: 10, e: -10};
    keysbyValue(Obj)

    /*  returned value: (Array)
    e,b,d,a,c
    */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.