Remove Duplicates from Javascript Array

Published Oct 10, 2022

Problem

You have an array of objects and you want to remove duplicates from it.

const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 3, name: 'Jack' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 4, name: 'Jill' },
  { id: 3, name: 'Jack' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 5, name: 'Jenny' },
  { id: 4, name: 'Jill' },
  { id: 3, name: 'Jack' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
]

Solutions

Using Set

const unique = [...new Set(arr.map((item) => item.id))].map((id) => {
  return arr.find((item) => item.id === id)
})

Using reduce

const unique = arr.reduce((acc, current) => {
  const x = acc.find((item) => item.id === current.id)
  if (!x) {
    return acc.concat([current])
  } else {
    return acc
  }
}, [])

Using filter

const unique = arr.filter((item, index, self) => {
  return index === self.findIndex((t) => t.id === item.id)
})

References

Found a mistake?

Every post is a Markdown file so contributing is simple as following the link below and pressing the pencil icon inside GitHub to edit it.

Edit on GitHub

© 2026 blackkspydo