EN
JavaScript - remove all duplicates from array of objects
0
points
In this article, we would like to show you how to remove all duplicates from an array of objects in JavaScript.
1. Practical example
In this section, we present a practical example of how to use filter() and findIndex() methods to remove duplicate elements from an array of objects.
// ONLINE-RUNNER:browser;
let array = [
{ type: 1, name: 'a' },
{ type: 2, name: 'b' },
{ type: 2, name: 'b' },
];
array = array.filter(
(value, index, self) => index === self.findIndex((item) => item.type === value.type && item.name === value.name)
);
console.log(JSON.stringify(array));
2. Array inside object
In this example, we present how to use filter() and findIndex() methods to remove duplicate elements from an array of objects which is placed inside an object.
// ONLINE-RUNNER:browser;
const object = {
array: [
{ type: 1, name: 'a' },
{ type: 2, name: 'b' },
{ type: 2, name: 'b' }
]
};
object.array = object.array.filter(
(value, index, self) => index === self.findIndex((item) => item.type === value.type && item.name === value.name)
);
console.log(JSON.stringify(object.array));