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

JavaScript 中从多个对象数组提取唯一值的正确实现方法

原代码问题说明
  • 双重循环逻辑存在错误:每次遍历array5的元素时,仅和array1的第一个元素对比就直接break退出内层循环,没有完成全量匹配,无法实现去重效果。
  • 对象为引用类型,不能直接用全等判断是否重复,需要根据你指定的categoryName作为去重维度做唯一性校验。
正确实现方案

方案1:合并数组后基于Set去重(推荐,时间复杂度O(n)性能最优)

适用于需要拿到两个数组合并后所有不重复的对象,每个categoryName仅保留一个:

let array1 = [
    { categoryName: "category 1" },
    { categoryName: "category 2" },
    { categoryName: "category 3" },
    { categoryName: "category 4" },
];

let array5 = [
    { categoryName: "category 1" },
    { categoryName: "category 2" },
    { categoryName: "category 3" },
    { categoryName: "category 4" },
    { categoryName: "category 5" },
];

// 合并两个数组
const merged = [...array1, ...array5];
const nameSet = new Set();
const uniqueResult = [];

for (const item of merged) {
  if (!nameSet.has(item.categoryName)) {
    nameSet.add(item.categoryName);
    uniqueResult.push(item);
  }
}

console.log(uniqueResult);
// 输出:[ {categoryName: "category 1"}, {categoryName: "category 2"}, {categoryName: "category 3"}, {categoryName: "category 4"}, {categoryName: "category 5"} ]

方案2:提取仅在单个数组中存在的独有元素

适用于需要拿到两个数组各自独有的、不在另一个数组中出现的元素:

// 筛选出array1有、array5没有的元素
const onlyArr1 = array1.filter(item => !array5.some(i => i.categoryName === item.categoryName));
// 筛选出array5有、array1没有的元素
const onlyArr5 = array5.filter(item => !array1.some(i => i.categoryName === item.categoryName));
// 合并得到所有独有元素
const uniqueOnly = [...onlyArr1, ...onlyArr5];

console.log(uniqueOnly);
// 示例输出:[ {categoryName: "category 5"} ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:39:05