Remove duplicate objects from array in javascript


To remove duplicate objects from an array in JavaScript, you can use the filter method and indexOf method. Here’s an example:

const originalArray = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Jane'},
  {id: 1, name: 'John'},
  {id: 3, name: 'Bob'},
  {id: 2, name: 'Jane'}
];

const newArray = originalArray.filter((obj, index, self) => 
  index === self.findIndex((t) => (
    t.id === obj.id && t.name === obj.name
  ))
);

console.log(newArray);

This code creates a new array (newArray) by filtering out duplicate objects from the original array (originalArray). The filter method is used to iterate over each object in the array, and the indexOf method is used to determine if the object already exists in the new array.

The filter method takes a callback function that is called once for each object in the array. The self.findIndex method is used to find the index of the first occurrence of the object in the array. If the index of the current object is equal to the index of the first occurrence of the object in the array, then the object is added to the new array.

The newArray contains only the unique objects from the original array.