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

JavaScript数组过滤问题:循环致重复结果,求优化方案

问题:从newList中过滤出不在people里的新人员

需求是通过people数组过滤newList数组,找出其中不在people中的新人员。现有代码使用for循环结合filter方法,得到了含重复的嵌套数组结果,期望得到仅包含bran和john的数组,需要避开循环解决重复问题。

现有代码

const people = [
    { "name": "jerry" },
    { "name": "tom" },
    { "name": "alex" }
]
const newList = [
    { "name": "bran" },
    { "name": "jerry" },
    { "name": "john" }
]

const new_people = []

for (const pp of people) {
    let result = newList.filter(newL => newL.name != pp.name)
    if (result) {
        new_people.push(result)
    }
}

console.log(new_people)

当前输出

[
  [ { name: 'bran' }, { name: 'john' } ],
  [ { name: 'bran' }, { name: 'jerry' }, { name: 'john' } ],
  [ { name: 'bran' }, { name: 'jerry' }, { name: 'john' } ]
]

期望输出

[ { name: 'bran' }, { name: 'john' } ]

问题分析

现有代码逻辑完全偏离需求:每次遍历people里的一个元素,就把newList中不等于该元素的项过滤出来并push到数组,最终得到的是多次过滤结果的集合,而非「newList中所有不在people里的项」。

解决方案

不需要嵌套循环,先把people中的名字提取到Set(查找效率更高),再直接用filter筛选newList即可:

const people = [
    { "name": "jerry" },
    { "name": "tom" },
    { "name": "alex" }
]
const newList = [
    { "name": "bran" },
    { "name": "jerry" },
    { "name": "john" }
]

// 提取people中的所有名字存入Set,实现O(1)时间复杂度的查找
const existingNames = new Set(people.map(person => person.name));
// 过滤newList,保留名字不在已有集合中的人员
const new_people = newList.filter(item => !existingNames.has(item.name));

console.log(new_people);

这段代码会直接输出期望的结果,同时避免了不必要的循环嵌套,效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:48:26