Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Sort object by numeric value

I have the following object:

{ key1: 5, key2: 3, key3: 1}

I now want to sort it by value so that I get:

{ key3: 1, key2: 2, key1: 5

I tried:

Object.keys(c).map(function (key) {return obj[key]});

But it didn't change the order.

Upvotes: 2

Views: 71

Answers (2)

Andrew Willems
Andrew Willems

Reputation: 12458

Convert the object to an array of arrays and then sort based on the second element in each subarray.

var obj = { key1: 5, key2: 3, key3: 1};
var arr = [];

for (prop in obj) {
  arr.push([prop, obj[prop]]);
}

arr.sort(compare);

function compare(a, b) {
  return a[1] - b[1];
}

document.querySelector("p").innerHTML = "<pre>" + JSON.stringify(arr, null, 2) + "</pre>";
<p></p>

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You can only sort the keys in an array, because objects have no order.

var obj = { key1: 5, key2: 3, key3: 1 },
    keys = Object.keys(obj);

keys.sort(function (a, b) {
    return obj[a]- obj[b];
});
document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');

Upvotes: 0

Related Questions