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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay