Home > Software engineering >  How to sort descending order with an Object result in NodeJs
How to sort descending order with an Object result in NodeJs

Time:01-30

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

CodePudding user response:

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.

CodePudding user response:

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 ] ]
  •  Tags:  
  • Related