Open In App

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:

Using Set

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

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

const uniqueArray =
    Array.from(new Set(array.map(obj =>
        JSON.stringify(obj))))
        .map(str => JSON.parse(str));

console.log(uniqueArray);

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

Using filter() and indexOf() method

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

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' } ]
Article Tags :