Angular中如何移除对象数组中的所有重复项?
对象数组按指定规则去重的最佳方法
现有如下对象数组:
obj.arr = new Array(); obj.arr.push({place:"1",name:"true"}); obj.arr.push({place:"1",name:"false"}); obj.arr.push({place:"2",name:"false"}); obj.arr.push({place:"2",name:"false"}); obj.arr.push({place:"3",name:"false"}); obj.arr.push({place:"3",name:"true"});
需要实现按place字段去重,且对于同一place的项,优先保留name为"true"的条目;若同一place下没有name为"true"的项,则保留任意一个name为"false"的条目,最终得到结果:
[{place:"1",name:"true"}, {place:"2",name:"false"}, {place:"3",name:"true"}]
推荐方法:使用Map实现高效去重
利用Map的键唯一性特性,遍历数组时按规则更新Map中的值,最后将Map转换为数组,时间复杂度为O(n),适合处理大数据量:
// 处理逻辑 const uniqueMap = new Map(); obj.arr.forEach(item => { // 若当前place未存入Map,或当前项name为true,则更新Map if (!uniqueMap.has(item.place) || item.name === "true") { uniqueMap.set(item.place, item); } }); // 将Map的值转换为数组,覆盖原数组 obj.arr = Array.from(uniqueMap.values());
替代方法:使用reduce实现(小数据量适用)
如果数组规模较小,也可以用reduce方法实现,逻辑更直观但时间复杂度为O(n²):
obj.arr = obj.arr.reduce((result, current) => { const match = result.find(item => item.place === current.place); if (!match) { result.push(current); } else if (current.name === "true") { // 替换为name为true的项 result[result.indexOf(match)] = current; } return result; }, []);
内容的提问来源于stack exchange,提问作者ben zarb adem
相关产品推荐
相关产品推荐

