如何基于属性值移除响应中的重复数组?
移除数组中重复
attribute_value的对象 嘿,我完全懂你的需求——就是要让每个attribute_value只对应一个数组项,把其他重复的整个对象都删掉对吧?其实你之前尝试的filter方法完全可行,可能只是差了个用来跟踪已出现值的小工具,我给你具体的实现方案:
核心思路
用一个Set来记录已经遇到过的attribute_value,遍历数组的时候,只保留那些attribute_value还没在Set里出现过的项,同时把这个值存入Set,这样后续遇到重复的就直接过滤掉。
代码示例
假设你的原始数组长这样:
const originalArray = [ { attribute_value: 1, name: "项1" }, { attribute_value: 1, name: "项2" }, { attribute_value: 1, name: "项3" }, { attribute_value: 2, name: "项A" }, { attribute_value: 2, name: "项B" }, { attribute_value: 3, name: "项X" } ];
实现去重的代码:
// 初始化一个空Set来存已经见过的attribute_value const seenValues = new Set(); // 用filter过滤数组 const uniqueArray = originalArray.filter(item => { // 如果当前值没出现过,就加入Set并保留这个对象 if (!seenValues.has(item.attribute_value)) { seenValues.add(item.attribute_value); return true; } // 已经出现过的话就过滤掉 return false; });
运行后uniqueArray里就只会保留每个attribute_value对应的第一个出现的对象:
// 输出结果 [ { attribute_value: 1, name: "项1" }, { attribute_value: 2, name: "项A" }, { attribute_value: 3, name: "项X" } ]
进阶:保留最后出现的重复项
如果你想保留每个attribute_value最后一次出现的对象,只需要先反转数组,过滤后再反转回去就行:
const seenValues = new Set(); const uniqueArrayLast = [...originalArray] .reverse() .filter(item => { if (!seenValues.has(item.attribute_value)) { seenValues.add(item.attribute_value); return true; } return false; }) .reverse();
这个方法效率很高,因为Set的查找和添加操作都是O(1)的,整个过程只需要遍历一次数组,比嵌套循环或者用数组includes的方法快多了~
内容的提问来源于stack exchange,提问作者Santosh
相关产品推荐
相关产品推荐

