0

Say I have an object like:

{A:5, B:3, C:-7, D:0}

I want to get an Array of its keys in asec/desc order like:

['C','D','B','A']

What is the best way to achieve this?

0

2 Answers 2

4

You can simply sort the keys, with Array.prototype.sort with the difference between the values of the corresponding keys, like this

console.log(Object.keys(data).sort(function(a, b) {
    return data[a] - data[b];
}));
# [ 'C', 'D', 'B', 'A' ]

To sort in the reverse order, simply find the difference between the values of b and a, like this

console.log(Object.keys(data).sort(function(a, b) {
    return data[b] - data[a];
}));
# [ 'A', 'B', 'D', 'C' ]
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that's so neat!
1

use Object.keys(obj) which gives an array that you can then sort on the keys using whatever ordering you like.

Comments

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.