Cover image for Removing repetitions from Array using the class Set

Removing repetitions from Array using the class Set

gabrielrufino profile image Gabriel Rufino ・1 min read

I was watching a course on Udemy and I figure out a very cool way of removing eventual repetitions of elements of an array.

It is the combination of the class Set with the Spread Operator.


Allows storage of unique values of any type.

Example of a set:

const set = new Set([1, 2, 3, 3, 4, 5, 5])
console.log(set) // Set {1, 2, 3, 4, 5}

Click here to know more about the class Set.

Spread operator

It will serve to spread the elements of the resulting Set.

Example of how the spread operator works:

const a = [1, 2, 3]
const b = [4, 5, 6]

const c = [...a, ...b]
console.log(c) // [1, 2, 3, 4, 5, 6]

Click here to learn more about the Spread operator.

Combining both

Now, we can combine both and remove the repetitions:

const initial = [1, 2, 2, 3, 4, 4, 8, 8]
const set = new Set(initial)
const final = [...set]

console.log(final) // [1, 2, 3, 4, 8]

Posted on by:

gabrielrufino profile

Gabriel Rufino


Fullstack Developer around JavaScript stack. Solving problems, generating value!


markdown guide

I think there are two points that are worth clarifying.

  1. You aren't removing anything from the array -- you're producing a new array without duplicates.
  2. Any information due to ordering of items in the array is lost.

So, this is really about producing an array to represent the set of items in another array, which is what you're actually doing. :)

EDIT: Actually, as Sets are iterated in insertion order, the relative orders are preserved, but not the indices.


Hahahaha how much preciousness. Let me guess, are u a functional programmer? Congratz

My intention here isn't to be precise with my words. It's totally possible to understand the "removing"

I'm sorry, Mr. English. But, thank you!!