typescript 获取对象数组中重复对象的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53212020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get list of duplicate objects in an array of objects
提问by ua_boaz
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' }
];
回答by ggorlen
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).
您可以使用Array#reduce
基于id
键的计数器查找表,然后用于Array#filter
删除查找表中仅出现一次的任何项目。时间复杂度为 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]));
回答by Aljosha Novakovic
You haven't clarified whether two objects with different ids, but the same "name" count as a duplicate. I will assume those do not count as a duplicate; in other words, only objects with the same id will count as duplicate.
您还没有澄清两个具有不同 id 的对象,但相同的“名称”是否算作重复。我会假设那些不算作重复;换句话说,只有具有相同 id 的对象才算作重复。
let ids = {};
let dups = [];
values.forEach((val)=> {
if (ids[val.id]) {
// we have already found this same id
dups.push(val)
} else {
ids[val.id] = true;
}
})
return dups;
回答by HMagdy
Let's say you have:
假设你有:
arr = [
{ id:10, name: 'someName1' },
{ id:10, name: 'someName2' },
{ id:11, name: 'someName3' },
{ id:12, name: 'someName4' }
]
So, to get unique items:
因此,要获得独特的物品:
unique = arr
.map(e => e['id'])
.map((e, i, final) => final.indexOf(e) === i && i)
.filter(obj=> arr[obj])
.map(e => arr[e]);
Then, result will be
那么,结果将是
unique = [
{ id:10, name: 'someName1' },
{ id:11, name: 'someName3' },
{ id:12, name: 'someName4' }
]
And, to get duplicate ids:
并且,要获得重复的 ID:
duplicateIds = arr
.map(e => e['id'])
.map((e, i, final) => final.indexOf(e) !== i && i)
.filter(obj=> arr[obj])
.map(e => arr[e]["id"])
List of IDs will be
ID 列表将是
duplicateIds = [10]
Thus, to get duplicates objects:
因此,要获取重复的对象:
duplicate = arr.filter(obj=> dublicateIds.includes(obj.id));
Now you have it:
现在你拥有了:
duplicate = [
{ id:10, name: 'someName1' },
{ id:10, name: 'someName2' }
]
回答by Ori Drori
With lodash you can use _.groupBy()
to group elements by their id
. Than _.filter()
out groups that have less than two members, and _.flatten()
the results:
随着lodash可以使用_.groupBy()
由他们的组元素id
。比_.filter()
少于两个成员的组,_.flatten()
结果:
const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
const result = _.flow([
arr => _.groupBy(arr, 'id'), // group elements by id
g => _.filter(g, o => o.length > 1), // remove groups that have less than two members
_.flatten // flatten the results to a single array
])(values);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
回答by Akrion
With lodash you can solve this with filter
and countBy
for complexity of O(n)
:
随着lodash你可以解决这个问题filter
,并countBy
为复杂性O(n)
:
const data = [{ id: 10,name: 'someName1' }, { id: 10,name: 'someName2' }, { id: 11,name: 'someName3' }, { id: 12,name: 'someName4' } ]
const counts = _.countBy(data, 'id')
console.log(_.filter(data, x => counts[x.id] > 1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
You could do the same with ES6 like so:
你可以像这样对 ES6 做同样的事情:
const data = [{ id: 10,name: 'someName1' }, { id: 10,name: 'someName2' }, { id: 11,name: 'someName3' }, { id: 12,name: 'someName4' } ]
const countBy = (d, id) => d.reduce((r,{id},i,a) => (r[id] = a.filter(x => x.id == id).length, r),{})
const counts = countBy(data, 'id')
console.log(data.filter(x => [x.id] > 1))
回答by Saurabh
Try this
试试这个
function checkDuplicateInObject(propertyName, inputArray) {
var seenDuplicate = false,
testObject = {};
inputArray.map(function(item) {
var itemPropertyName = item[propertyName];
if (itemPropertyName in testObject) {
testObject[itemPropertyName].duplicate = true;
item.duplicate = true;
seenDuplicate = true;
}
else {
testObject[itemPropertyName] = item;
delete item.duplicate;
}
});
return seenDuplicate;
}
referred from : http://www.competa.com/blog/lets-find-duplicate-property-values-in-an-array-of-objects-in-javascript/
引用自:http: //www.competa.com/blog/lets-find-duplicate-property-values-in-an-array-of-objects-in-javascript/
回答by ControlAltDel
create a function, objectsEqual
, and then use a filter
创建一个函数,objectsEqual
然后使用过滤器
values.filter(function(num, elem) {
for (var i = 0; i < values.length; i++) {
if (i == num) continue;
if (objectsEqual(values[num], values[i])) return true;
}
return false;
}
回答by Niall
You can use an array to store unique elements and use filter on values to only return duplicates.
您可以使用数组来存储唯一元素,并对值使用过滤器以仅返回重复项。
const unique = []
const duplicates = values.filter(o => {
if(unique.find(i => i.id === o.id && i.name === o.name)) {
return true
}
unique.push(o)
return false;
})