How to Convert an Array to Set in JavaScript

Here are four ways to convert an array to a set in JavaScript:

  1. Using Set constructor
  2. Using Array.prototype.map()
  3. Using Array.prototype.forEach()
  4. Using Array.prototype.reduce()

Method 1: Using Set constructor

let moneyheist = ["Tokyo", "Nairobi", "Berlin", "Oslo", "Moscow"]

let moneyheist_set = new Set(moneyheist)

console.log(moneyheist_set)

Output

Set(5) { 'Tokyo', 'Nairobi', 'Berlin', 'Oslo', 'Moscow' }

The new keyword is to create a new set and pass the JavaScript array as its first and only argument. Next, you can see that the array is converted to the Set.

Method 2: Using Array.prototype.map()

let arr = [11, 31, 21, 19, 46];

let set = new Set();
arr.map(item => set.add(item));

console.log(set);

Output

Set(5) { 11, 31, 21, 19, 46 }

Method 3: Using Array.prototype.forEach()

let arr = [11, 31, 21, 19, 46];

let set = new Set();
arr.forEach(item => set.add(item));
 
console.log(set);

Output

Set(5) { 11, 31, 21, 19, 46 }

Method 4: Using Array.prototype.reduce()

let arr = [11, 31, 21, 19, 46];

let set = new Set();

arr.reduce((_, e) => set.add(e), null);
 
console.log(set);

Output

Set(5) { 11, 31, 21, 19, 46 }

That’s it.

Related posts

JavaScript Set to Array

JavaScript Array to Object