How to Remove Duplicates from an Array of Objects in JavaScript?

Estimated read time 1 min read

To remove duplicates from an array of objects in JavaScript, you can use the reduce() method and store unique objects in an accumulator based on a unique identifier like the id property. Here’s an example:

let arr = [
  {id: 1, name: "John"},
  {id: 2, name: "Jane"},
  {id: 1, name: "John"},
  {id: 3, name: "Jim"}
];

let uniqueArr = arr.reduce((acc, curr) => {
  let exists = acc.find(item => item.id === curr.id);
  if (!exists) {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(uniqueArr);

This code removes duplicates from the array [{id: 1, name: "John"}, {id: 2, name: "Jane"}, {id: 1, name: "John"}, {id: 3, name: "Jim"}] and logs the modified array: [{id: 1, name: "John"}, {id: 2, name: "Jane"}, {id: 3, name: "Jim"}].

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply