I want to get all objects with the same id, into a new array.
In below data, first object with id: 1 is repeated at 3rd and 5th position, so I need to store 1st, 3rd and 5th position object into new array. Same thing if more id is repeated in data
Data:
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' },
]
My code:
// 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)
}
My incorrect output
[
{ 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' }
]
expected output
[
{ 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' }
]
In incorrect output section object with { id: 1, file: 'test1.xlsx' } is getting repeated 2 times which should not be the case and same thing with the other duplicate entry as well.
I think, I was able to figure that my current problem, and the reason why the output is incorrect is maybe because the find() method only returns first element.
I have searched solutions online, and many people have recommended to use reduce, or filter method but I'm not able to figure out how to implement it.