简体   繁体   中英

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]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM