Sometimes, we want to get a list of duplicate objects in an array of objects with JavaScript.
In this article, we’ll look at how to get a list of duplicate objects in an array of objects with JavaScript.
How to get a list of duplicate objects in an array of objects with JavaScript?
To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods.
For instance, we write:
const values = [{
id: 10,
name: 'someName1'
},
{
id: 10,
name: 'someName2'
},
{
id: 11,
name: 'someName3'
},
{
id: 12,
name: 'someName4'
}
];
const duplicateIds = values
.map(v => v.id)
.filter((v, i, vIds) => vIds.indexOf(v) !== i)
const duplicates = values
.filter(obj => duplicateIds.includes(obj.id));
console.log(duplicates)
to get an array of value
entries with the same id
and put them into duplicates
.
To do this, we get the id
s of the items with the same id
by calling map
to get the id
s into their own array.
Then we call filter
with a callback that checks if indexOf
returns the same value as index i
to get all the id
s of the duplicate items in the duplicateIds
array.
Next, we call values.filter
with a callback to check if the id
of the item is in the duplicateIds
array.
As a result, we get:
[
{
"id": 10,
"name": "someName1"
},
{
"id": 10,
"name": "someName2"
}
]
for the value of duplicates
.
Conclusion
To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods.