How to use filter() and indexOf() method In Javascript

  • We use the filter() method to iterate over each object in the original array.
  • For each object in the array, we use indexOf() to check if the index of the current object is equal to the index of its first occurrence. If it is, it means the object is unique and we keep it in the filtered array.
  • The filter method constructs a new array containing only the unique objects based on the condition described above.
  • Finally, we print the unique array, which contains only the unique objects from the original array.

Example: This example shows the implementation of the above approach.

JavaScript
const array = [
    { id: 1, name: 'geeks' },
    { id: 2, name: 'for' },
    { id: 1, name: 'geeks' }
];

const uniqueArray = array.filter((obj,
    index, self) =>
    index === self.findIndex(o =>
        o.id === obj.id &&
        o.name === obj.name
    )
);
console.log(uniqueArray);

Output
[ { id: 1, name: 'geeks' }, { id: 2, name: 'for' } ]

How to Remove Duplicate Objects from an Array in JavaScript?

In JavaScript, it’s a common example that the arrays contain objects and there might be a possibility that the objects may or may not be unique. Removing these duplicate objects from the array and getting the unique ones is a common task in Web Development.

These are the following approaches:

Table of Content

  • Using Set
  • Using filter() and indexOf() method

Similar Reads

Using Set

We know that the JavaScript Set stores only the unique values, so we use the set to filter out duplicate objects.To use the set, we need to convert each object to a string using JSON.stringify() method, then add them to the set.Then filter the array based on whether the set already contains the string representation or not.At the end print the unique object of the array....

Using filter() and indexOf() method

We use the filter() method to iterate over each object in the original array.For each object in the array, we use indexOf() to check if the index of the current object is equal to the index of its first occurrence. If it is, it means the object is unique and we keep it in the filtered array.The filter method constructs a new array containing only the unique objects based on the condition described above.Finally, we print the unique array, which contains only the unique objects from the original array....