我有一个包含对象数组的对象。
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"}
我知道这个问题已经有很多答案了,但请耐心等待。。。
数组中的某些对象可能具有您不感兴趣的其他财产,或者您只想查找只考虑财产子集的唯一对象。
考虑下面的数组。假设您想仅考虑propOne和propTwo来查找此数组中的唯一对象,而忽略可能存在的任何其他财产。
预期结果应仅包括第一个和最后一个对象。代码如下:
常量数组=[{propOne:“a”,propTwo:“b”,第三题:“我没有参与……”},{propOne:“a”,propTwo:“b”,someOtherProperty:“没有人关心这个…”},{propOne:'x',propTwo:'y',yetAotherJunk:“我真的一文不值”,这个:“我有一些别人没有的东西”}];常量uniques=[…新集合(array.map(x=>JSON.stringify(((o)=>({propOne:o.propOne,propTwo:o.propTwo}))(x) ))].map(JSON.parse);console.log(uniques);
如果您可以使用诸如下划线或lodash之类的Javascript库,我建议查看它们库中的_.uniq函数。来自lodash:
_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])
基本上,您传入数组,这里是一个对象文本,然后传入要在原始数据数组中删除重复项的属性,如下所示:
var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];
var non_duplidated_data = _.uniq(data, 'name');
更新:Lodash现在也引入了.uniqBy。
另一种方法是使用reduce函数,并使用一个新数组作为累加器。如果累加器数组中已经有一个同名的对象,那么不要将其添加到那里。
let list = things.thing;
list = list.reduce((accumulator, thing) => {
if (!accumulator.filter((duplicate) => thing.name === duplicate.name)[0]) {
accumulator.push(thing);
}
return accumulator;
}, []);
thing.things = list;
我添加了这个答案,因为我找不到与InternetExplorer11兼容的好的、可读的es6解决方案(我使用babel来处理箭头函数)。问题是IE11没有没有polyfill的Map.values()或Set.values)。出于同样的原因,我使用filter()[0]来获取第一个元素,而不是find()。
如果您可以等到所有添加之后再消除重复项,典型的方法是首先对数组进行排序,然后消除重复项。排序避免了在遍历每个元素时扫描数组的N*N方法。
“消除重复项”函数通常称为unique或uniq。一些现有的实现可以结合这两个步骤,例如原型的uniq
如果你的图书馆还没有,这篇文章没有什么想法可以尝试(还有一些需要避免:-)!我个人认为这是最直接的:
function unique(a){
a.sort();
for(var i = 1; i < a.length; ){
if(a[i-1] == a[i]){
a.splice(i, 1);
} else {
i++;
}
}
return a;
}
// Provide your own comparison
function unique(a, compareFunc){
a.sort( compareFunc );
for(var i = 1; i < a.length; ){
if( compareFunc(a[i-1], a[i]) === 0){
a.splice(i, 1);
} else {
i++;
}
}
return a;
}