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

JavaScript统计二维数组重复项 生成附带计数的扩展二维数组

解决方法

核心逻辑说明

你原来的代码是利用数组隐式转为字符串的特性做统计键,得到的是键值对形式的统计结果,只需额外把统计结果转换为你需要的二维数组结构即可,修改后的代码如下:

let colors = [
  ['blue', 'green', 5.00, 57],
  ['blue', 'green', 5.00, 57],
  ['yellow', 'green', 8.30, 84],
  ['blue', 'green', 5.00, 57],
  ['orange', 'blue', 7.00, 0],
  ['yellow', 'green', 8.30, 84],
];

function count_duplicate() {
  // 用对象做临时统计存储
  const countMap = {};
  for (let i = 0; i < colors.length; i++) {
    // 用JSON.stringify保证子数组序列化后唯一,避免子项含逗号导致的统计错误
    const key = JSON.stringify(colors[i]);
    countMap[key] = (countMap[key] || 0) + 1;
  }
  // 遍历统计结果转换为目标二维数组
  const counts = Object.entries(countMap).map(([key, count]) => {
    // 把序列化的key转回原数组,追加计数
    return [...JSON.parse(key), count];
  });
  console.log(counts);
  return counts;
}

count_duplicate();

运行输出

[
  ['blue', 'green', 5, 57, 3],
  ['yellow', 'green', 8.3, 84, 2],
  ['orange', 'blue', 7, 0, 1]
]

如果需要保留数值的小数位数(比如5.00不自动转为5),可以把子数组的数值项先统一转成字符串再做统计,序列化时会保留格式

内容的提问来源于stack exchange,提问作者Matthäus L.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:27:00