You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 lowest
  • Object.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:12:34