Here are four ways to convert an array to a set in JavaScript:
- Using Set constructor
- Using Array.prototype.map()
- Using Array.prototype.forEach()
- 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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.