Languages
[Edit]
EN

JavaScript - create and initialize Set

0 points
Created by:
Jun-L
963

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

 

See also

  1. JavaScript - print Set items in the console

References

  1. Set() constructor - JavaScript | MDN

Alternative titles

  1. JavaScript - create Set and initialize its values
  2. JavaScript - create Set with values initialized on creation
  3. JavaScript - initialize set values on creation
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join