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

4
  • 3
    you can not sort the object's keys, but you can sort only the keys, if you like. Commented Jul 27, 2016 at 15:35
  • 2
    Object's keys cannot guarantee its indext Commented Jul 27, 2016 at 15:35
  • 1
    your expected result does not match the title of the post. do you need descending order (title) or ascending order (example)? Commented Jul 27, 2016 at 15:44
  • 1
    @Nina Scholz: Sorry my fault. It should be ascending. Commented Jul 27, 2016 at 16:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This way can guide me. Thank you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.