EN
JavaScript - create and initialize Set
0
points
In this article, we would like to show you how to create and initialize Set in JavaScript.
1. Create Set from array
In this example, we use array to initialize Set values on creation.
// ONLINE-RUNNER:browser;
const mySet = new Set(['a', 'b', 'b', 'c']);
console.log(...mySet); // a, b, c
Note:
All duplicate elements will be removed.
2. Create Set then add values
In this example, we create a set using Set() constructor and then we use add() method to add values to it.
// ONLINE-RUNNER:browser;
const mySet = new Set();
mySet.add('a');
mySet.add('b');
mySet.add('c');
console.log(...mySet); // a, b, c
3. Create Set from iterable
Sets can take any iterable in their constructor. It means that we can also pass an iterable (like a string) to the constructor. It will be split into individual values and duplicate elements will be removed.
// ONLINE-RUNNER:browser;
var mySet = new Set('aabbcc');
console.log(...mySet); // a, b, c