我有一个包含对象数组的对象。
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"}
使用ES6“reduce”和“find”数组助手方法的简单解决方案
工作效率高,非常好!
"use strict";
var 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"
});
// the logic is here
function removeDup(something) {
return something.thing.reduce(function (prev, ele) {
var found = prev.find(function (fele) {
return ele.place === fele.place && ele.name === fele.name;
});
if (!found) {
prev.push(ele);
}
return prev;
}, []);
}
console.log(removeDup(things));
这是一种通用的方法:传入一个函数,该函数测试数组的两个元素是否相等。在本例中,它比较所比较的两个对象的名称和位置财产的值。
ES5答案
函数removeDucplicates(arr,equals){var originalArr=arr.slice(0);变量i,len,val;arr.length=0;对于(i=0,len=原始Arr.length;i<len;++i){val=原始Arr[i];if(!arr.some(函数(项){return equals(项,val);})){arr.push(val);}}}函数thingsEqual(thing1,thing2){返回thing1.place==thing2.place&&thing.name===thing.name;}var事物=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];删除重复项(things,thingsEqual);console.log(things);
ES3原始答案
function arrayContains(arr, val, equals) {
var i = arr.length;
while (i--) {
if ( equals(arr[i], val) ) {
return true;
}
}
return false;
}
function removeDuplicates(arr, equals) {
var originalArr = arr.slice(0);
var i, len, j, val;
arr.length = 0;
for (i = 0, len = originalArr.length; i < len; ++i) {
val = originalArr[i];
if (!arrayContains(arr, val, equals)) {
arr.push(val);
}
}
}
function thingsEqual(thing1, thing2) {
return thing1.place === thing2.place
&& thing1.name === thing2.name;
}
removeDuplicates(things.thing, thingsEqual);