1

I have an array object like this:

var obj = {
  a : [0, 25],
  b : [1, 33],
  c : [2, 66], 
  d : [3, 12],
  etc..
}

How can I sort it according to the second value of the array ? It should be like that after sorting:

var obj = {
  d : [3, 12],
  a : [0, 25],
  b : [1, 33], 
  c : [2, 66],
  etc..
}

I found a similar issue but it didnt help: Sort by object key in descending order on Javascript/underscore

Community
  • 1
  • 1
Burak Özdemir
  • 510
  • 8
  • 18

1 Answers1

2

You can only sort the keys of an object.

var obj = { a: [0, 25], b :[1, 33], c: [2, 66], d: [3, 12] },
    keys = Object.keys(obj);

keys.sort(function (a, b) {
    return obj[a][1] - obj[b][1];
});

console.log(keys);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392