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

JavaScript:不使用sort()实现数组唯一值统计并生成指定对象

不使用sort()统计数组元素出现次数

实现思路

直接遍历数组,用对象(或Map)记录每个元素的出现次数,遍历过程中实时更新计数,无需排序操作。

代码实现

方法1:使用普通对象统计

const users = [
  '21000316',
  '21000316',
  '21000316',
  '21000316',
  '22000510',
  '22000510',
  '22000510',
  '22000510'
];

const countResult = {};

// 遍历数组,更新计数
for (const id of users) {
  // 若id已存在则计数+1,否则初始化为1
  countResult[id] = (countResult[id] || 0) + 1;
}

console.log(countResult);
// 输出:{ '21000316': 4, '22000510': 4 }

方法2:使用Map统计(兼容特殊键场景)

如果需要处理非字符串/数字的键,用Map更灵活,最后可转为普通对象:

const users = [
  '21000316',
  '21000316',
  '21000316',
  '21000316',
  '22000510',
  '22000510',
  '22000510',
  '22000510'
];

const countMap = new Map();

for (const id of users) {
  countMap.set(id, (countMap.get(id) || 0) + 1);
}

// 将Map转换为目标格式的普通对象
const countResult = Object.fromEntries(countMap);

console.log(countResult);
// 输出:{ '21000316': 4, '22000510': 4 }

说明

两种方法均只需遍历一次数组(时间复杂度O(n)),无需依赖sort(),直接完成去重和计数的合并操作,比先排序再统计的效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:30:53