The ways to remove duplicate items in an Array of Objects

The ways to remove duplicate items in an Array of Objects.

Use new Set method

const fruits = [
	{ id: 1, name: 'apple' },
    { id: 2, name: 'banana' },
    { id: 3, name: 'apple' },
    { id: 4, name: 'banana' }
]

const fruitsUpdated = Array.from(new Set(fruits.map(e => e.name)))
 .map(name => {
   return fruits.find(e => e.name === name)
 })
 
console.log(fruitsUpdated)
 // [
 //   { id: 1, name: 'apple' },
 //   { id: 2, name: 'banana' },
 // ]


Reuse with a helper function:

function removeDuplicateObjects(arr) {
	return Array.from(new Set(arr.map(e => e.name)))
      .map(name => {
      return arr.find(e => e.name === name)
    })
}

console.log(removeDuplicateObjects(fruits))


Use reduce method

const fruits = [
	{ id: 1, name: 'apple' },
    { id: 2, name: 'banana' },
    { id: 3, name: 'apple' },
    { id: 4, name: 'banana' }
]

const fruitsUpdated = fruits.reduce((arr, currentItem) => {
  const x = arr.find(item => item.name === currentItem.name);
  if (!x) {
    return arr.concat([currentItem]);
  } else {
    return arr;
  }
}, []);
 
console.log(fruitsUpdated)
 // [
 //   { id: 1, name: 'apple' },
 //   { id: 2, name: 'banana' },
 // ]


Reuse with a helper function:

function removeDuplicateObjects(ObjArr) {
	return ObjArr.reduce((arr, currentItem) => {
      const x = arr.find(item => item.name === currentItem.name);
      if (!x) {
        return arr.concat([currentItem]);
      } else {
        return arr;
      }
    }, []);
}

console.log(removeDuplicateObjects(fruits))


TheArray.from method creates a new, shallow-copied Array instance from an array-like or iterable object.
TheSet object lets you store unique values of any type, whether primitive values or object references.
Thereduce method executes a reducer function (that you provide) on each element of the array, resulting in single output value.


© 2019 4codev

Created with love by Sil.