Sometimes you may need to convert a Set to an array, for example to be able to use Array.prototype
methods like .filter()
. In order to do so, use [Array.from()](<http://stackoverflow.com/documentation/javascript/187/arrays/2333/converting-an-array-like-object-list-to-an-array#t=201608050855343146834>)
or [destructuring-assignment](<http://stackoverflow.com/documentation/javascript/616/destructuring-assignment#t=201702150551283063641>)
:
var mySet = new Set([1, 2, 3, 4]);
//use Array.from
const myArray = Array.from(mySet);
//use destructuring-assignment
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}