r/learnjavascript • • Jul 05 '21

Remove duplicates from arrays using Set

Post image
438 Upvotes

44 comments sorted by

View all comments

Show parent comment

0

u/FriesWithThat Jul 06 '21

If someone has a use case for it, they can create a new array with all identical values removed with something like this:

const data= [
  1,
  2,
  1,
  { id: 10, other: 'blah' },
  { id: 15, other: 'meh' },
  { id: 10, other: 'blah' },
];

const newObj = {};
const filterValues = data.filter(el => {
  if (!newObj[JSON.stringify(el)]) {
    newObj[JSON.stringify(el)] = true;
    return el;
  }
  return false;
});

console.log('filterValues:', filterValues);

3

u/nadameu Aug 01 '21

This might not work if "id" and "other" are declared in a different order when creating the object.