我有一个包含对象数组的对象。
obj = {};
obj.arr = new Array();
obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});
我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
TypeScript函数将数组过滤到其唯一元素,其中唯一性由给定的谓词函数决定:
function uniqueByPredicate<T>(arr: T[], predicate: (a: T, b: T) => boolean): T[] {
return arr.filter((v1, i, a) => a.findIndex(v2 => predicate(v1, v2)) === i);
}
不打字员:
function uniqueByPredicate(arr, predicate) {
return l.filter((v1, i, a) => a.findIndex(v2 => predicate(v1, v2)) === i);
}
您也可以使用地图:
const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());
完整样本:
const things = new Object();
things.thing = new Array();
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});
const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());
console.log(JSON.stringify(dedupThings, null, 4));
结果:
[
{
"place": "here",
"name": "stuff"
},
{
"place": "there",
"name": "morestuff"
}
]
带过滤器的内衬(保留订单)
在数组中查找唯一id。
arr.filter((v,i,a)=>a.findIndex(v2=>(v2.id===v.id))===i)
如果顺序不重要,映射解决方案将更快:使用映射解决方案
多个财产独有(地点和名称)
arr.filter((v,i,a)=>a.findIndex(v2=>['place','name'].every(k=>v2[k] ===v[k]))===i)
所有财产都是唯一的(对于大型阵列来说,这将很慢)
arr.filter((v,i,a)=>a.findIndex(v2=>(JSON.stringify(v2) === JSON.stringify(v)))===i)
通过用findLastIndex替换findIndex来保留最后一次出现。
arr.filter((v,i,a)=>a.findLastIndex(v2=>(v2.place === v.place))===i)