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.
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.
xxxxxxxxxx
1
let array = [
2
{ type: 1, name: 'a' },
3
{ type: 2, name: 'b' },
4
{ type: 2, name: 'b' },
5
];
6
7
array = array.filter(
8
(value, index, self) => index === self.findIndex((item) => item.type === value.type && item.name === value.name)
9
);
10
11
console.log(JSON.stringify(array));
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.
xxxxxxxxxx
1
const object = {
2
array: [
3
{ type: 1, name: 'a' },
4
{ type: 2, name: 'b' },
5
{ type: 2, name: 'b' }
6
]
7
};
8
9
object.array = object.array.filter(
10
(value, index, self) => index === self.findIndex((item) => item.type === value.type && item.name === value.name)
11
);
12
13
console.log(JSON.stringify(object.array));