-1

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"
}
TIMMY123
  • 35
  • 5

1 Answers1

0

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]);
}
Prime
  • 2,544
  • 1
  • 3
  • 19