Remove duplicates from Javascript Array

Blackkspydo

0 views 0 reactions 2022-10-10

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

Leave a reaction if you liked this post! 🧡

Subscribe to the newsletter

Get emails from me about Lorem ipsum dolor sit, amet consectetur adipisicing elit. Libero, ducimus..

3 subscribers including my Mom – 23 issues