Node.js中如何对统计数组重复值的对象结果进行降序排序?
Solution: Sort Count Object by Value (Descending)
Got it, let's get your count object sorted by occurrence values in descending order! The key thing to note here is that while modern JavaScript objects preserve insertion order, your original function just adds keys as they appear in the array. To sort by the count values, we need to convert the object to an array, sort it, then convert it back.
Here's the modified function:
function countRequirementIds() { const counts = {}; const sampleArray = RIDS; // Step 1: Count occurrences (same as your original logic) sampleArray.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; }); // Step 2: Convert object to array of [key, value] pairs const sortedEntries = Object.entries(counts) // Step 3: Sort by the count value in descending order .sort((a, b) => b[1] - a[1]); // Step 4: Convert sorted array back to object const sortedCounts = Object.fromEntries(sortedEntries); return sortedCounts; }
Test Result:
- Original output:
{ "1": 4, "2": 5, "4": 1, "13": 4 } - Modified function output:
{ "2": 5, "1": 4, "13": 4, "4": 1 }(matches your expected result!)
Breakdown of Changes:
Object.entries(counts): Turns your count object into an array like[["1",4], ["2",5], ["4",1], ["13",4]].sort((a, b) => b[1] - a[1]): Sorts this array by the second element of each pair (the count) from highest to lowestObject.fromEntries(sortedEntries): Converts the sorted array back into a properly ordered object
This works in all modern browsers and Node.js versions supporting ES2019 or later. For older environments, you can add polyfills for Object.entries and Object.fromEntries, but this should cover most common use cases today.
内容的提问来源于stack exchange,提问作者Deepak Dev
相关产品推荐
相关产品推荐

