【发布时间】:2021-05-30 01:25:40
【问题描述】:
我想将所有具有相同 id 的对象放入一个新数组中。
在下面的数据中,id: 1 的第一个对象在第 3 和第 5 位置重复,所以我需要将第 1、第 3 和第 5 位置对象存储到新数组中。如果在数据中重复更多 id,也是一样
数据:
const data = [
{ id: 1, file: 'test1.xlsx' },
{ id: 3, file: 'test1.xlsx' },
{ id: 1, file: 'test2.xlsx' },
{ id: 5, file: 'test2.xlsx' },
{ id: 1, file: 'test3.xlsx' },
{ id: 7, file: 'test3.xlsx' },
{ id: 8, file: 'test4.xlsx' },
{ id: 9, file: 'test4.xlsx' },
{ id: 9, file: 'test5.xlsx' },
{ id: 10, file: 'test5.xlsx' },
{ id: 9, file: 'test6.xlsx' },
]
我的代码:
// arr = data
// headerKey = 'id'
const getDuplicates = (arr, headerKey) => {
return arr
.map((el, i) => {
return arr.find((element, index) => {
if (i !== index && element[headerKey] === el[headerKey]) {
return el
}
})
})
.filter((x) => x)
}
我的输出不正确
[
{ id: 1, file: 'test2.xlsx' },
{ id: 1, file: 'test1.xlsx' },
{ id: 1, file: 'test1.xlsx' },
{ id: 9, file: 'test5.xlsx' },
{ id: 9, file: 'test4.xlsx' },
{ id: 9, file: 'test4.xlsx' }
]
预期输出
[
{ id: 1, file: 'test1.xlsx' },
{ id: 1, file: 'test2.xlsx' },
{ id: 1, file: 'test3.xlsx' },
{ id: 9, file: 'test4.xlsx' },
{ id: 9, file: 'test5.xlsx' },
{ id: 9, file: 'test6.xlsx' }
]
在不正确的输出部分中,{ id: 1, file: 'test1.xlsx' } 的对象被重复了 2 次,这不应该是这种情况,其他重复条目也是如此。
我想,我能够弄清楚我当前的问题,输出不正确的原因可能是因为find()方法只返回第一个元素。
我在网上搜索了解决方案,很多人建议使用reduce,或filter方法,但我不知道如何实现。
【问题讨论】:
标签: javascript arrays algorithm duplicates