Remove Duplicate Objects from an Array

Last Updated On Monday 29th Nov 2021

JavaScript remove duplicate objects from Array

Lets Take an array of objects and remove those that are duplicates objects.

JavaScript Remove Duplicates from array of objects

Let’s say we have an array of objects and some of those objects are duplicates.
How do we know they’re duplicates ?
Maybe they have the same id number which we know is to be unique.

	const array = [
  { id: 1, name: "Adam" },
  { id: 2, name: "Alice" },
  { id: 3, name: "Ben" },
  { id: 4, name: "John" },
  { id: 5, name: "Ado" },
  { id: 1, name: "Adam" },
  { id: 2, name: "Alice" },
  { id: 4, name: "John" },
];
	

Let’s Create new variable unique

  • The reduce method is a higher order function so we need to pass a function into it.

Get a unique list of objects by key

Use Spread Operator or Use Array.from

With Spread

	const getUnique = (arr) => [...array.reduce((map, each) => map.set(each.id, each), new Map()).values()];
	

With Array.from

	const getUnique = (arr) => Array.from(arr.reduce((map, each) => map.set(each.id, each), new Map()).values());
	
	console.log(getUnique(array))

// [
//   { id: 1, name: 'Adam' },
//   { id: 2, name: 'Alice' },
//   { id: 3, name: 'Ben' },
//   { id: 4, name: 'John' },
//   { id: 5, name: 'Ado' },
// ]
	

References

Spread Syntax

Array From

Reduce