Clueless_Coder
Clueless_Coder

Reputation: 603

Sort javascript object key into array based on object's value

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]

Upvotes: 3

Views: 408

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

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)

Upvotes: 5

Related Questions