Converting Sets to arrays

suggest change

Sometimes you may need to convert a Set to an array, for example to use Array.prototype methods like .filter(). Use Array.from or spread. The two lines below are alternatives; declaring myArray twice in one scope is a syntax error.

var mySet = new Set([1, 2, 3, 4]);
const myArray = Array.from(mySet);
// const myArray = [...mySet];

Now you can filter the array to contain only even numbers and convert it back to Set using Set constructor:

mySet = new Set(myArray.filter(x => x % 2 === 0));

mySet now contains only even numbers:

console.log(mySet); // Set {2, 4}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents