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

JavaScript实现HashMap按值降序排序并限制返回前10条记录

代码修改建议:获取前10条高频记录

需求

我不擅长编程,找不到类似示例,希望修改现有代码,让处理后的结果按值从高到低排序并只返回前10条最高值的记录。

现有代码

function getMostFrequent(arr) {
  const hashmap = arr.reduce( (acc, val) => {
   acc[val] = (acc[val] || 0 ) + 1
   return acc
},{})
return Object.entries(hashmap).sort((a, b) => b[1] - a[1]);
}

console.log(getMostFrequent(output));

当前输出

[
  [ '300', 173 ], [ '200', 31 ], [ '500', 31 ],
  [ '800', 29 ],  [ '700', 28 ], [ '600', 26 ],
  [ '400', 20 ],  [ '290', 11 ], [ '160', 10 ],
  [ '220', 10 ],  [ '250', 9 ],  [ '100', 8 ],
  [ '240', 8 ],   [ '260', 8 ],  [ '350', 8 ],
  [ '370', 8 ],   [ '230', 7 ],  [ '390', 7 ],
  [ '210', 6 ],   [ '280', 6 ],  [ '110', 5 ],
  [ '140', 5 ],   [ '150', 5 ],  [ '270', 5 ],
  [ '310', 5 ],   [ '320', 5 ],  [ '120', 4 ],
  [ '130', 4 ],   [ '330', 4 ],  [ '340', 4 ],
  [ '170', 3 ],   [ '190', 3 ],  [ '360', 2 ],
  [ '380', 2 ],   [ '', 1 ]
]

修改后的代码

function getMostFrequent(arr) {
  const hashmap = arr.reduce( (acc, val) => {
   acc[val] = (acc[val] || 0 ) + 1
   return acc
},{})
// 排序后截取前10条记录
return Object.entries(hashmap).sort((a, b) => b[1] - a[1]).slice(0, 10);
}

console.log(getMostFrequent(output));

改动说明

你的原代码已经完成了统计元素出现次数和按次数从高到低排序的核心逻辑,只需要在排序结果后添加.slice(0, 10)方法,就能直接截取前10条记录。

修改后运行的输出会是:

[
  [ '300', 173 ], [ '200', 31 ], [ '500', 31 ],
  [ '800', 29 ],  [ '700', 28 ], [ '600', 26 ],
  [ '400', 20 ],  [ '290', 11 ], [ '160', 10 ],
  [ '220', 10 ]
]

如果存在次数相同的元素(比如原输出中的200和500都出现31次),它们会保留排序后的顺序并被纳入前10条结果中。

内容的提问来源于stack exchange,提问作者Reptilian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:10:32