La forma de la vieja escuela de agregar todos los valores de una matriz en el Set es:
// for the sake of this example imagine this set was created somewhere else // and I cannot construct a new one out of an array let mySet = new Set() for(let item of array) { mySet.add(item) } ¿Hay una forma más elegante de hacer esto? ¿Quizás mySet.add(array) o mySet.add(...array) ?
PD: Sé que ambos no funcionan
Si bien Set API sigue siendo muy minimalista, puede usar Array.prototype.forEach y acortar un poco su código:
array.forEach(item => mySet.add(item)) // alternative, without anonymous arrow function array.forEach(mySet.add, mySet)Aquí hay una forma funcional, devolviendo un nuevo conjunto:
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' }Este es en mi opinión el más elegante.
// 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);