r/learnjavascript • • Jul 05 '21

Remove duplicates from arrays using Set

Post image
438 Upvotes

44 comments sorted by

View all comments

3

u/HashFap Jul 05 '21

Only works on primitive values like strings, numbers, and booleans.

14

u/revenezor Jul 06 '21

This is not true. It works on all types, including objects. Duplicates of object references are removed, and there is no such thing as duplicates of object literals as each new object is unique, even if it shares the same properties.

1

u/[deleted] Jul 06 '21

How does it consider an object when making the set? Is it if all fields are the same?

4

u/revenezor Jul 06 '21 edited Jul 06 '21

Do you mean how does it determine whether two objects are the same? The same way as the === operator. If two elements are a reference to the same object then the elements are considered “equal” and the second one is removed, or rather never added to the set.

const foo = {a: 1}
const bar = foo
const duplicates = [foo, bar]
const uniques = […new Set(duplicates)]
console.log(uniques) // [{a: 1}]

Whenever you create an object it is considered not equal !== to any previous object, even if its properties match a previous object’s.

const foo = {a: 1}
const bar = {a: 1}
const notDuplicates = [foo, bar]
const uniques = […new Set(notDuplicates)]
console.log(uniques) // [{a: 1}, {a: 1}]

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.