DEV Community

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

Posted on

2 1

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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)