Reputation: 603
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
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