我有一个包含对象数组的对象。
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"}
如果数组包含对象,则可以使用此方法删除重复的
const persons= [
{ id: 1, name: 'John',phone:'23' },
{ id: 2, name: 'Jane',phone:'23'},
{ id: 1, name: 'Johnny',phone:'56' },
{ id: 4, name: 'Alice',phone:'67' },
];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];
如果删除基于电话的重复项,只需将m.id替换为m.phone
const unique = [...new Map(persons.map((m) => [m.phone, m])).values()];
如果您发现需要经常基于特定字段从数组中删除重复的对象,那么创建一个可以从项目中任何位置导入的独特(数组、谓词)函数可能是值得的。这看起来像
const things = [{place:"here",name:"stuff"}, ...];
const distinctThings = distinct(things, thing => thing.place);
不同的函数可以使用上面许多好答案中给出的任何实现。最简单的方法是使用findIndex:
const distinct = (items, predicate) => items.filter((uniqueItem, index) =>
items.findIndex(item =>
predicate(item) === predicate(uniqueItem)) === index);
如果您可以使用诸如下划线或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。