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

如何从嵌套数组生成以元素第1索引出现频率为值的对象?

问题分析与代码修正

你的需求是生成一个对象:键为数组中所有唯一元素,值为该元素作为嵌套数组**第1索引(即子数组第二个元素)**的出现频率,未出现过的元素值为0。原代码存在以下问题:

  • 循环条件错误:使用了未定义的matches.length,实际应为test.length
  • 统计逻辑混乱:赋值语句混淆了不同元素的计数关系,没有正确累加目标位置元素的出现次数
  • 未初始化所有唯一元素的默认值为0,导致计数逻辑完全失效

修正后的代码(基础for循环版)

const test = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]];
const result = {};

// 第一步:收集所有唯一元素并初始化值为0
const allElements = new Set();
test.forEach(item => {
  allElements.add(item[0]);
  allElements.add(item[1]);
});
allElements.forEach(el => {
  result[el] = 0;
});

// 第二步:统计每个元素在子数组第1索引位置的出现次数
for (let i = 0; i < test.length; i++) {
  const targetEl = test[i][1];
  result[targetEl] += 1;
}

console.log(result);

更简洁的reduce版

const test = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]];

const result = test.reduce((acc, [first, second]) => {
  // 确保第一个元素已初始化
  if (acc[first] === undefined) acc[first] = 0;
  // 累加第二个元素的计数
  acc[second] = (acc[second] || 0) + 1;
  return acc;
}, {});

console.log(result);

两种方式都能得到你期望的输出:

{
  '1': 0,
  '2': 0,
  '3': 2,
  '4': 1,
  '5': 1,
  '6': 2,
  '7': 1,
  '8': 1,
  '9': 2,
  '10': 0
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:40:18