简体   繁体   中英

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

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.

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 ] ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM