loading...

Discussion on: Basic Javascript: Removing Duplicates from an Array

Collapse
nickytonline profile image
Nick Taylor (he/him)

With a Set, you can just do

function removeDuplicates(array) {
  return [...new Set(array)]
}
Enter fullscreen mode Exit fullscreen mode

I have some other examples here.

Collapse
ronancodes profile image
Ronan Connolly 🛠

I get a TypeScript error for trying to expand the set.
This works though:

function removeDuplicates(array) {
  return Array.from(new Set(array));
}

Seems like the simplest solution.

Collapse
lesha profile image
lesha

While I totally agree with you, this post is filed under #beginners. Beginner programmers need to build a solid understanding of how things work under the hood (doing deduplication manually) and then use abstractions like Set.

Collapse
mschleeweiss profile image
Marc Schleeweiß

Using a Set is literally part of the blog post. None of the other possible solutions from the post are low level. In fact they all use lambda expressions, which is even more complicated to grasp than a Set, which consists of unique values (per definition).

Collapse
clarity89 profile image
Alex K.

While you do have a point there, I think array.splice(0, array.length, ...(new Set(array))) would be more confusing for beginners ;)

Thread Thread
lesha profile image
lesha

that's a nightmare tbh

Thread Thread
tails128 profile image
Tails128

I would say that is something which should not be taught to new devs, cause it will push them in the wrong direction, to be fair.

Collapse
worc profile image
worc

i don't know that i would call a set an abstraction of manual deduplication. for a beginner, a set just is a set of unique values. how you get there manually, or what implementation your runtime is using to guarantee that uniqueness doesn't feel like a beginner topic.