3

Let say I have an object with numbers as key and string as value

var obj = { '24': 'Sean', '17': 'Mary', '88': 'Andrew', '46': 'Kelvin' } 

Is there an easy way to sort the keys into an array based on their value where the result will looks like this:

[88,46,17,24] 

1 Answer 1

5

Here's one way to do it:

var obj = { '24': 'Sean', '17': 'Mary', '88': 'Andrew', '46': 'Kelvin' } var sortedKeys = Object.keys(obj).sort(function(a, b) { return obj[a].localeCompare(obj[b]); }).map(Number) console.log(sortedKeys)

Omit the .map() part if you are happy for the result to be an array of strings rather than numbers.

Further reading:

Or the same thing but with ES6 arrow functions:

const sortedKeys = Object.keys(obj) .sort((a, b) => obj[a].localeCompare(obj[b])) .map(Number) 
Sign up to request clarification or add additional context in comments.

5 Comments

Nice catch with the string values!
That was quick and nicely done. Just learn about .localeCompare(). Thanks for the answer
@Phil - Thanks! I'll admit I didn't think of it to begin with, but when I ran my code without the .map() I happened to notice the strings in the output. I notice that other than that you independently came up with exactly the same thing except with arrow functions, which is certainly a lot neater assuming they're acceptable to the OP. Given that you deleted that answer I might add arrow functions to mine.
@nnnnnn no point having two identical answers and yours was first :). FYI, you can also convert the array to numeric via .map(Number)
@Phil - D'oh! I knew that, and in fact RobG had just mentioned it in a (now deleted) comment so I should've remembered. I'll edit that in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.