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

NodeJS:如何避免向嵌套数组中添加重复键名?

解决数组合并时过滤重复键名的问题

原函数存在两个核心问题:

  • 用for...in遍历数组拿到的是索引值(如0、1),而非子数组本身,导致检查逻辑完全偏离预期
  • indexOf只能匹配整个子数组,无法单独校验子数组的第一个元素(键名)

修改后的函数

function arrayCombine(arrayOfValues, arrayOfValues2) {
    // 提取已有键名存入Set,提升重复检查效率
    const existingKeys = new Set(arrayOfValues.map(item => item[0]));
    
    // 遍历第二个数组的每个子数组
    for (const item of arrayOfValues2) {
        const key = item[0];
        if (!existingKeys.has(key)) {
            arrayOfValues.push(item);
            existingKeys.add(key); // 同步更新已存在键集合
        }
    }
    return arrayOfValues;
}

测试验证

用你提供的示例数组测试:

const arrayOfValues = [
  [ 'test', 11 ],
  [ 'test2', 13 ],
  [ 'test3', 16 ],
];

const arrayOfValues2 = [
  [ 'test4', 12 ],
  [ 'test2', 25 ],
];

console.log(arrayCombine(arrayOfValues, arrayOfValues2));

输出结果:

[
  [ 'test', 11 ],
  [ 'test2', 13 ],
  [ 'test3', 16 ],
  [ 'test4', 12 ]
]

重复键名test2的项已被成功过滤,仅保留原数组中的对应项。

补充说明

  • 使用Set存储已存在键名,查找时间复杂度为O(1),比每次遍历数组检查(O(n))效率更高,适合大数据量场景
  • 后续若要实现值合并逻辑(如重复键名时累加值),只需将if分支内的push操作改为更新原数组对应项的值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:45:36