我有一个包含对象数组的对象。
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"}
另一种方法是使用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()。
使用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));
这是我的解决方案,将实际数组添加到键值对象中,其中键将是唯一标识,值可以是对象或整个对象的任何属性。
说明:具有重复项的主数组将转换为键/值对象如果Id已存在于唯一对象中,则该值将被覆盖。最后,只需将唯一对象转换为数组。
getUniqueItems(array) {
const unique = {};
// here we are assigning item.name but it could be a complete object.
array.map(item => unique[item.Id] = item.name);
// here you can transform your array item like {text: unique[key], value: key} but actually you can do what ever you want
return Object.keys(unique).map(key => ({text: unique[key], value: key}));
})
);
}