The Set
constructor in JavaScript provides a convenient way to create a new Set
from an iterable, such as an array. By passing the iterable as an argument to the Set
constructor, it automatically adds all unique elements of the iterable to the new Set
. For example:
const arr = ['foo', 'bar', 'baz']; const set = new Set(arr); console.log(set); // Set(3) {"foo", "bar", "baz"}
In this example, the array "arr
" contains three elements (i.e., 'foo'
, 'bar'
, and 'baz'
). When you use the Set
constructor with the array as an argument, it creates a new Set
containing these unique elements.
It's important to note that Set
objects in JavaScript store only unique values. Therefore, if there are duplicates in the array, they won't be added to the Set
. Consider the following example:
const arrWithDuplicates = [ 'foo', 'foo', 'bar', 'foo', 'baz' ]; const set = new Set(arrWithDuplicates); console.log(set); // Set(3) {"foo", "bar", "baz"}
In this case, even though the array "arrWithDuplicates
" contains duplicate entries of 'foo'
, the resulting Set
only retains the unique values — i.e., 'foo'
, 'bar'
, and 'baz'
. Duplicates are automatically removed when constructing a Set
.
This behavior makes Sets useful tool for handling collections of unique values in JavaScript, providing an efficient way to eliminate duplicates from an array.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.