Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 614
David Rhoden Avatar asked Feb 11 '11 12:02

David Rhoden


1 Answers

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"];
like image 66
Tim Down Avatar answered Sep 20 '22 14:09

Tim Down