DEV Community

Cover image for Remove duplicate Objects within an Array by Object key.
Luke Secomb
Luke Secomb

Posted on

Remove duplicate Objects within an Array by Object key.

A quick and easy way to remove duplicate Objects within an Array of Objects by key.

function removeDuplicateObjectsByKey(array, fieldToDuplicateCheck) {
  const newArray = []
  const arrayKeys = []

  array.forEach((item) => {
    // check if we don't already have the value within the arrayKeys array
    if (!arrayKeys.includes(item[fieldToDuplicateCheck])) {
      // push this value to the arrayKeys array
      arrayKeys.push(item[fieldToDuplicateCheck])
      // push this object to the newArray array
      newArray.push(item)
    }
  })

  // return the newArray with the filtered out duplicate objects
  return newArray
}

// A test array of objects. In a real world situation you would have more than just the 'name' key on the objects
const initialArrayOfObjects = [
  {
    name: '🐑',
  },
  {
    name: '🐑',
  },
  {
    name: '🐫',
  },
  {
    name: '🦕',
  },
  {
    name: '🦕',
  },
]

// will filter out the duplicates by the 'name' field
let removeDuplicateObjects = removeDuplicateObjectsByKey(initialArrayOfObjects, 'name')
// [ { name: '🐑' }, { name: '🐫' }, { name: '🦕' } ]
Enter fullscreen mode Exit fullscreen mode

Github Gist

Cover Photo Credits to Charl Folscher

Top comments (0)