in javascript, is there an easy way to sort key-value pairs by the value, and return the key?

David Rhoden picture David Rhoden · Feb 11, 2011 · Viewed 25.5k times · Source

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

Answer

Tim Down picture Tim Down · Feb 11, 2011

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"];