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
}
1

1 Answer 1

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)
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.