获取对象数组中重复对象的列表 [英] Get list of duplicate objects in an array of objects
本文介绍了获取对象数组中重复对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取对象数组中的重复对象.假设对象如下所示.
I am trying to get duplicate objects within an array of objects. Let's say the object is like below.
values = [
{ id: 10, name: 'someName1' },
{ id: 10, name: 'someName2' },
{ id: 11, name: 'someName3' },
{ id: 12, name: 'someName4' }
];
重复的对象应该返回如下:
Duplicate objects should return like below:
duplicate = [
{ id: 10, name: 'someName1' },
{ id: 10, name: 'someName2' }
];
推荐答案
您可以使用 Array#reduce
根据id
键制作一个计数器查找表,然后使用Array#filter
删除任何在查找表中只出现一次的项目.时间复杂度为 O(n).
You can use Array#reduce
to make a counter lookup table based on the id
key, then use Array#filter
to remove any items that appeared only once in the lookup table. Time complexity is O(n).
const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
const lookup = values.reduce((a, e) => {
a[e.id] = ++a[e.id] || 0;
return a;
}, {});
console.log(values.filter(e => lookup[e.id]));
这篇关于获取对象数组中重复对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文