8

This is the hashmap I have

{
"LY": 43,
"US": 19,
"IN": 395,
"IR": 32,
"EG": 12,
"SA": 17,
}

How can I sort in descending order, with respect to the key values using javascript/lodash?

The expected output is:

{
"IN": 395,
"LY": 43,
"IR":32,
"US":19,
"SA":17,
"EG":12
}
Arun Mohan
  • 898
  • 3
  • 18
  • 37
  • 2
    Possible duplicate of [How to sort an associative array by its values in Javascript?](http://stackoverflow.com/questions/5199901/how-to-sort-an-associative-array-by-its-values-in-javascript) – djechlin Jan 22 '16 at 06:11

1 Answers1

5

Use a different data structure

You can't control the order of keys in Object

you can use an Array when it's coming to sorting data,

var obj = {
  "LY": 43,
  "US": 19,
  "IN": 395,
  "IR": 32,
  "EG": 12,
  "SA": 17,
};

var array = [];
for (var key in obj) {
  array.push({
    name: key,
    value: obj[key]
  });
}

var sorted = array.sort(function(a, b) {
  return (a.value > b.value) ? 1 : ((b.value > a.value) ? -1 : 0)
});
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129