DEV Community

Discussion on: 1 line of code: How to remove all duplicates from an Array

Collapse
 
michaelcurrin profile image
Michael Currin

Worth explaining this separately when used with array instead of sets

const x = ["abc", "def"]
const y = [...x]
// ["abc", "def"]
Enter fullscreen mode Exit fullscreen mode

And modifying x and y won't affect the other.

Then bringing in set

const x = ["abc", "def", "abc"]
const y = new Set(x)
// Set(["abc", "def"])
const z = [...y]
// ["abc", "def"]
Enter fullscreen mode Exit fullscreen mode

And the the original post does that in one line in a function

Collapse
 
michaelcurrin profile image
Michael Currin

Also worth adding that you might want to stop once you have a set and not convert it back to an array.

Why?

Lookup time from a set is constant to check if a value is in a set while in an array of 1000 elements worst case you have to go through 1000 elements until you find the one at the end.

Secondly when you convert from array to set, the order will be lost. Sets are inherently unordered. So when you convert from set to array you will not get the order of the original array. So you might as well keep the set.

Collapse
 
qm3ster profile image
Mihail Malo

It's actually specced to preserve insertion order: developer.mozilla.org/en-US/docs/W...

(...spread operator calls y[Symbol.iterator], which is specced to be the same as what is returned by .values() on Set)

Thread Thread
 
michaelcurrin profile image
Michael Currin

Oh interesting, in Python it is unordered.

Collapse
 
martinkr profile image
Martin Krause

Thank you for the explanation.