简体   繁体   中英

How to sort Object mapping in Javascript in descending order of VALUES?

I have an Object map of account numbers and balances.

Balance: {
"a": "1000"
"b": "3000"
"c": "2000"
}

How do I sort this balance by descending order by balance amount so it becomes:

Balance: {
"b": "3000"
"c": "2000"
"a": "1000"
}

JavaScript objects are not ordered. It is meaningless to try to "sort" them. If you want to sort an object by its values, you can sort the keys by values, and then retrieve the associated values like the below example.

 var myObj = { 'b': 3000, 'c': 1000, 'a': 2000 }, keys = Object.keys(myObj), i, len = keys.length; keys.sort((a, b) => myObj[a] < myObj[b]? 1: -1); for (i = 0; i < len; i++) { k = keys[i]; console.log(k + ':' + myObj[k]); }

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