Deepak Dev
Deepak Dev

Reputation: 101

How to sort descending order with an Object result in NodeJs

I am using the below function to get number of duplicated values in an array.But i want to get this result sorted descending order with respect to the values.

function countRequirementIds() {
    const counts = {};
    const sampleArray = RIDS;
    sampleArray.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; });
    console.log(typeof counts); //object
    return counts
}

Output:

{
"1": 4,
"2": 5,
"4": 1,
"13": 4
}

required output:

{
"2": 5, 
"1": 4, 
"13": 4,
"4": 1,
}

Upvotes: 0

Views: 1444

Answers (2)

jblew
jblew

Reputation: 555

Javascript object keys are unordered as explained here: Does JavaScript guarantee object property order?

So sorting objects by keys is impossible. However if order is of a matter for you I would suggest using array of tuples:

const arrayOfTuples = [
  [ "1", 4],
  [ "2", 5],
  [ "4", 1],
  [ "13", 4],
]

arrayOfTuples.sort((a,b) => b[1] - a[1]);
console.log(arrayOfTuples);
// => [ [ '2', 5 ], [ '1', 4 ], [ '13', 4 ], [ '4', 1 ] ]

Upvotes: 1

Shannon Starr
Shannon Starr

Reputation: 101

The sort command. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort Arrays of objects can be sorted by comparing the value of one of their properties.

Upvotes: 0

Related Questions