How to Remove Duplicate Objects from an Array
Last updated: December 5, 2022.
When working with an array of data objects like the one below (no values are functions), you can stringify each object and check with filter()
and findIndex()
if it is the first occurence of itself in the array.
Only the first occurence of each object is included in the new array output by filter()
:
const array = [
{ name:"Someone", id:"1" },
{ name:"Someone else", id:"2", f: function() { 2+2 }},
{ name:"Someone2", id:"1" },
{ name:"Someone else", id:"2", f: function() { 2+2 }}
];
// JSON Stringify method
const res = array.filter(function(item, index) {
return index === array.findIndex(function(obj) {
return JSON.stringify(item) === JSON.stringify(obj);
})
})
console.log(res);
// [
// { name: "Someone", id: "1" },
// { name: "Someone else", id: "2", f: function() { 2+2 } },
// { name: "Someone2", id: "1" }
// ]
However, if objects in the array contain functions, you should avoid using JSON.stringify()
because the functions will be ignored and removed from the new array!
Instead, you can use the solution below to filter by an identifying property such as id
:
const array = [
{ name:"Someone", id:"1" },
{ name:"Someone else", id:"2", f: function() { 2+2 } },
{ name:"Someone2", id:"1" },
{ name:"Someone else", id:"2", f: function() { 2+2 } }
];
// By identifier
const res = array.filter(function(item, index) {
return index === array.findIndex(function(obj) {
return item.id === obj.id;
})
})
console.log(res);
// [
// { name: "Someone", id: "1" },
// { name: "Someone else", id: "2", f: function() { 2+2 } },
// { name: "Someone2", id: "1" }
// ]
This solution can be extended to filter based upon multiple property values:
const array = [
{ name:"Someone", id:"1" },
{ name:"Someone else", id:"2", f: function() { 2+2 } },
{ name:"Someone2", id:"1" },
{ name:"Someone else", id:"2", f: function() { 2+3 } }
];
// By identifier
const res = array.filter(function(item, index) {
return index === array.findIndex(function(obj) {
return item.id === obj.id && item.name === obj.name &&
((item.f && obj.f) ? (item.f).toString() === (obj.f).toString() : true);
})
})
console.log(res);
// [
// { name: "Someone", id: "1" },
// { name: "Someone else", id: "2", f: function() { 2+2 } },
// { name: "Someone2", id: "1" }
// { name: "Someone else", id: "2", f: function() { 2+3 } },
// ]
Related posts
- Filter an existing array to make a new one using filter()
- Using JSON in JavaScript
- How to Remove Falsy Values from an Array