假设你有以下内容:
arr = [
{ id:10, name: 'someName1' },
{ id:10, name: 'someName2' },
{ id:11, name: 'someName3' },
{ id:12, name: 'someName4' }
]
因此,要获取唯一的项:
unique = arr
.map(e => e['id'])
.map((e, i, final) => final.indexOf(e) === i && i)
.filter(obj=> arr[obj])
.map(e => arr[e]);
然后,结果将会是
unique = [
{ id:10, name: 'someName1' },
{ id:11, name: 'someName3' },
{ id:12, name: 'someName4' }
]
而要获取重复的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"])
将列出ID列表
duplicateIds = [10]
因此,要获取重复的对象:
duplicate = arr.filter(obj=> dublicateIds.includes(obj.id));
现在你拥有它:
duplicate = [
{ id:10, name: 'someName1' },
{ id:10, name: 'someName2' }
]
感谢 https://reactgo.com/removeduplicateobjects/