我有一个包含对象数组的对象。
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);
}
var testArray= ['a','b','c','d','e','b','c','d'];
function removeDuplicatesFromArray(arr){
var obj={};
var uniqueArr=[];
for(var i=0;i<arr.length;i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = arr[i];
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);
Output:- [ 'a', 'b', 'c', 'd', 'e' ]
const uniqueElements = (arr, fn) => arr.reduce((acc, v) => {
if (!acc.some(x => fn(v, x))) { acc.push(v); }
return acc;
}, []);
const stuff = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"},
];
const unique = uniqueElements(stuff, (a,b) => a.place === b.place && a.name === b.name );
//console.log( unique );
[{
"place": "here",
"name": "stuff"
},
{
"place": "there",
"name": "morestuff"
}]