Sometimes, we want to remove duplicates form an array with JavaScript.
In this article, we’ll look at how to remove duplicates form an array with JavaScript.
How to remove duplicates form an array with JavaScript?
To remove duplicates form an array with JavaScript, we can use the sets and the array map method.
For instance, we write
const array = [
{ id: 123, value: "value1", name: "Name1" },
{ id: 124, value: "value2", name: "Name1" },
{ id: 125, value: "value3", name: "Name2" },
{ id: 126, value: "value4", name: "Name2" },
];
const names = [...new Set(array.map((a) => a.name))];
console.log(names);
to call array.map with a callback to map each array entry to the name property of each entry.
Then we create a new set with the mapped array with the Set constructor.
Finally, we use the spread operator to spread it back to an array.
Conclusion
To remove duplicates form an array with JavaScript, we can use the sets and the array map method.