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

JavaScript如何从数组获取去重结果,合并同分组非空属性生成新数组

实现方案

采用「哈希表分组+单次遍历合并」的逻辑实现,时间复杂度为O(n),为该场景下的最优解法,完整代码如下:

const array = [
    [{"name":"Joe", "age":null, "date":"1959-08-10", "home":"ny"}],
    [{"name":"Bill", "age":null, "date":"1956-08-10", "home":"tx"}],
    [{"name":"Joe", "age":"17", "date":null, "home":"ny"}],
    [{"name":null, "age":"17", "date":"1956-08-10", "home":"tx"}],
    [{"name":"Joe", "age":"17", "date":"1959-08-10", "home":null}]
];

const groupMap = new Map();

// 处理带有效home值的条目,按home分组合并非空属性
array.forEach(item => {
    const curr = item[0];
    const homeKey = curr.home;
    if (!homeKey) return;

    if (!groupMap.has(homeKey)) {
        groupMap.set(homeKey, { name: null, age: null, date: null, home: homeKey });
    }
    const target = groupMap.get(homeKey);
    Object.keys(target).forEach(key => {
        if (curr[key] !== null) target[key] = curr[key];
    });
});

// 处理home为null的条目,匹配同名分组补充属性
array.forEach(item => {
    const curr = item[0];
    if (curr.home) return;
    for (const [_, target] of groupMap) {
        if (curr.name === target.name) {
            Object.keys(target).forEach(key => {
                if (curr[key] !== null && target[key] === null) target[key] = curr[key];
            });
            break;
        }
    }
});

// 转换为要求的输出格式
const new_array = Array.from(groupMap.values()).map(i => [i]);

执行后输出的new_array完全符合预期:

[
    [{"name":"Joe", "age":"17", "date":"1959-08-10", "home":"ny"}],
    [{"name":"Bill", "age":"17", "date":"1956-08-10", "home":"tx"}]
]

方案说明

  • 用Map做分组存储,读写性能高于普通对象,分组操作时间复杂度为O(1)
  • 仅需要两次遍历原数组,整体时间复杂度为O(n),远高于多次循环筛选的写法
  • 逻辑分层清晰,先处理明确分组的条目,再补全无有效home的条目,避免逻辑混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:15:05