JavaScript Code


How to convert an array into a set in JavaScript?


Convert an array into a set in JavaScript

Given an array, write a JavaScript program to convert the array into a set.

Solution

To convert given array of elements into a set in JavaScript, use the Set() constructor. Pass the array as argument to Set() constructor, and it returns a set created from the elements of the array.

new Set(myArray);

Any duplicate elements in the array would be ignored in the resulting set.

Program

1. Convert the array vowelArray into a set vowelSet.

const vowelArray = ['a', 'e', 'i', 'o', 'u'];
const vowelSet = new Set(vowelArray);
console.log([...vowelSet]);


copyright @2022