0

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,
}
Deepak Dev
  • 101
  • 1
  • 7

2 Answers2

1

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 ] ]
jblew
  • 506
  • 3
  • 9
0

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.

  • 1
    You are right that this is a correct way of sorting arrays. However author of the question wanted sorting object keys which is not possible (or to be more specific it is not guaranteed by javascript specification): https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order :) – jblew Jan 30 '22 at 12:12
  • 1
    Actually I also had to check. I've never had a need to sort object keys, and JS is often so surprising that it's good to always check anything – jblew Jan 30 '22 at 12:16
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Tyler2P Jan 30 '22 at 20:30