如何用JavaScript找出数组中属性重复的对象
如何在JavaScript中找出数组里属性重复的对象
嘿,这个问题很常见,我来给你拆解一下怎么解决。从你给出的order数组来看,我们需要找出那些item_name、item_status和extras完全一致的对象——这里要注意,extras是数组,直接用对象全等符===是没法正确比较的,得先处理数组的比较逻辑。
下面给你两种实用的解决方案,分别适合不同的场景:
方法一:用哈希表(Map)统计,高效处理大数据量
这种方法时间复杂度是O(n),适合数组元素较多的情况。核心思路是给每个对象生成一个唯一的“特征字符串”,用Map统计这个字符串出现的次数,最后筛选出重复的对象。
代码示例
// 先定义你的完整数组(补全了你没写完的最后一项) const order = [ { "item_name": " Corn Pie", "item_status": "ready", "extras": ["French Fries","Bacon"] }, { "item_name": " Corn Pie", "item_status": "ready", "extras": ["French Fries","Bacon"] }, { "item_name": " Corn Pie", "item_status": "ready", "extras": ["French Fries","Bacon"] }, { "item_name": " Corn Pie", "item_status": "ready", "extras": ["French Fries","Bacon"] }, { "item_name": " Corn Pie", "item_status": "ready", "extras": [] }, { "item_name": " Corn Pie", "item_status": "preparing", "extras": ["French Fries"] } ]; // 生成对象的唯一特征字符串,把数组转成字符串方便比较 function getObjectKey(obj) { // 如果extras的元素顺序不影响重复判断,可以加上.sort():JSON.stringify(obj.extras.sort()) return `${obj.item_name}-${obj.item_status}-${JSON.stringify(obj.extras)}`; } // 方法1:返回每个重复组的第一个实例(去重后的重复对象) function findUniqueDuplicateItems(arr) { const itemCount = new Map(); const duplicates = []; // 第一次遍历:统计每个特征字符串的出现次数 arr.forEach(item => { const key = getObjectKey(item); itemCount.set(key, (itemCount.get(key) || 0) + 1); }); // 第二次遍历:筛选出出现次数>1的对象,且每个重复组只存一个 arr.forEach(item => { const key = getObjectKey(item); if (itemCount.get(key) > 1 && !duplicates.some(dup => getObjectKey(dup) === key)) { duplicates.push(item); } }); return duplicates; } // 方法2:返回所有重复出现的实例(比如前4个相同的对象都会被返回) function findAllDuplicateInstances(arr) { const itemCount = new Map(); const duplicates = []; arr.forEach(item => { const key = getObjectKey(item); const currentCount = (itemCount.get(key) || 0) + 1; itemCount.set(key, currentCount); // 只要不是第一次出现,就加入结果 if (currentCount > 1) { duplicates.push(item); } }); return duplicates; } // 测试使用 console.log(findUniqueDuplicateItems(order)); // 输出1个重复的Corn Pie对象 console.log(findAllDuplicateInstances(order)); // 输出4个重复的Corn Pie对象
方法二:用filter+some,适合小数据量
这种方法逻辑更直观,但时间复杂度是O(n²),数组大的时候效率会低一些,适合快速处理小型数组。
代码示例
// 深度比较两个对象是否完全相同 function isSameItem(itemA, itemB) { return itemA.item_name === itemB.item_name && itemA.item_status === itemB.item_status && // 同样,如果数组顺序不影响,可以改成JSON.stringify(itemA.extras.sort()) === ... JSON.stringify(itemA.extras) === JSON.stringify(itemB.extras); } // 找出所有重复出现的实例 function findDuplicatesWithFilter(arr) { return arr.filter((item, index) => { // 检查当前元素之后有没有和它相同的元素 return arr.some((otherItem, otherIndex) => otherIndex > index && isSameItem(item, otherItem)); }); } // 测试 console.log(findDuplicatesWithFilter(order)); // 输出前4个相同的Corn Pie对象
额外注意点
- 如果你的对象有多层嵌套结构,
JSON.stringify可能会失效(比如属性顺序不同但内容相同的对象),这时候需要写一个递归的深度比较函数来替代。 - 如果
extras数组的元素顺序不影响“重复”判断(比如["Bacon", "French Fries"]和["French Fries", "Bacon"]算同一个),记得在生成特征字符串或者比较的时候先给数组排序:obj.extras.sort()。
内容的提问来源于stack exchange,提问作者Miguel Sedek
相关产品推荐
相关产品推荐

