admin管理员组

文章数量:1325155

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
}

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
}
Share Improve this question edited Jan 22, 2016 at 6:19 Arun Mohan asked Jan 22, 2016 at 6:09 Arun MohanArun Mohan 9784 gold badges19 silver badges39 bronze badges 1
  • 2 Possible duplicate of How to sort an associative array by its values in Javascript? – djechlin Commented Jan 22, 2016 at 6:11
Add a ment  | 

1 Answer 1

Reset to default 5

Use a different data structure

You can't control the order of keys in Object

you can use an Array when it's ing 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)
});

本文标签: javascriptHow to sort a hashmap with respect to the valueStack Overflow