How to add an array of values to a Set
While Set
API is still very minimalistic, you can use Array.prototype.forEach
and shorten your code a bit:
array.forEach(item => mySet.add(item))
// alternative, without anonymous arrow function
array.forEach(mySet.add, mySet)
Here's a functional way, returning a new set:
const set = new Set(['a', 'b', 'c'])
const arr = ['d', 'e', 'f']
const extendedSet = new Set([ ...set, ...arr ])
// Set { 'a', 'b', 'c', 'd', 'e', 'f' }
This is IMO the most elegant
// for a new Set
const x = new Set([1,2,3,4]);
// for an existing Set
const y = new Set();
[1,2,3,4].forEach(y.add, y);
How about using the spread operator to easily blend your new array items into an existing set?
const mySet = new Set([1,2,3,4])
const additionalSet = [5,6,7,8,9]
mySet = new Set([...mySet, ...additionalSet])
JSFIDDLE
create a new Set:
//Existing Set
let mySet = new Set([1,2,3,4,5]);
//Existing Array
let array = [6,7,8,9,0];
mySet = new Set(array.concat([...mySet]));
console.log([...mySet]);
//or single line
console.log([...new Set([6,7,8,9,0].concat([...new Set([1,2,3,4,5])]))]);