How to Remove Duplicate Objects from Arrays in JavaScript

How to Remove Duplicate Objects from Arrays in JavaScript

Ferenc Almasi β€’ 2022 February 09 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

To remove duplicate objects from arrays in JavaScript, we can use a combination of sets and Array.filter:

Copied to clipboard! Playground
const duplicates = [
    { key: 'apple',  value: '🍎' },
    { key: 'banana', value: '🍌' },
    { key: 'banana', value: '🍌' }
]

const set = new Set()
const unique = duplicates.filter(item => {
    const alreadyHas = set.has(item.key)
    set.add(item.key)

    return !alreadyHas
})

This works by filtering through the array and adding one of the properties of the objects to a new set. The reason we are adding this to a new set is that sets are unique by nature. We then filter out those values that have already been added to the set. This way, we end up with an array of unique objects.

Unfortunately, since each object has a different reference, even if their properties match, we cannot simply do something like this:

Copied to clipboard! Playground
// ❌ This won't work
[...new Set(duplicates)]

// Because the reference will be different, even if the properties match
{ id: 1 } !== { id: 1 }

You can also copy the below function to your codebase to use it as an exported utility function in other places:

Copied to clipboard! Playground
const removeDuplicateObjects = (array, key) => {
    const set = new Set()

    return array.filter(item => {
        const alreadyHas = set.has(item[key])
        set.add(item[key])

        return !alreadyHas
    })
}

// Later call it in your app like so:
removeDuplicateObjects(array, 'key') <- looks for the "key" property
removeDuplicateObjects(array, 'value') <- looks for the "value" property
How to Remove Duplicate Objects from Arrays in JavaScript
If you would like to see more webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.