Reputation: 8484
The old school way of adding all values of an array into the Set
is:
// 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)
}
Is there a more elegant way of doing this? Maybe mySet.add(array)
or mySet.add(...array)
?
PS: I know both do not work
Upvotes: 258
Views: 247678
Reputation: 1691
This is in my opinion 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);
Upvotes: 51
Reputation: 845
How about using the spread operator to easily blend your new array items into an existing set?
let mySet = new Set([1,2,3,4])
const additionalSet = [5,6,7,8,9]
mySet = new Set([...mySet, ...additionalSet])
[JSFIDDLE][1] [1]: https://jsfiddle.net/clayperez/yjkxh9d8/9/
Upvotes: 18
Reputation: 61
Input the array in the first place, when you create the set. You'll get the set with all items in the array.
const array = [1,2,3,4,5]
let mySet = new Set(array)
console.log(mySet)
//Add new one element
mySet.add(6)
console.log(mySet)
//Add exist element
mySet.add(6)
console.log(mySet)
Upvotes: 0
Reputation: 92
let mySet = new Set(['a', 'b']);
let arrayToBeAdded = ['c', 'd'];
//convert the Set to an array, then concatenate both arrays, finally convert into a Set
mySet = Array.form(mySet).concat(arrayToBeAdded);
mySet = new Set(mySet);
//in single line
mySet = new Set(Array.form(mySet).concat(arrayToBeAdded));
Upvotes: 1
Reputation: 9315
You can also use Array.reduce()
:
const mySet = new Set();
mySet.add(42); // Just to illustrate that an existing Set is used
[1, 2, 3].reduce((s, e) => s.add(e), mySet);
Upvotes: 10
Reputation: 501
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])]))]);
Upvotes: 4
Reputation: 5061
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)
Upvotes: 253
Reputation: 5739
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' }
Upvotes: 131
Reputation: 73251
There's currently no addAll
method for Sets, but you have two options to simplify your life when working with them. The first one would be to extend the prototype. Before you do that, read this post and decide afterwards if the possible consequences are ok for your project/intended use.
if (!Set.prototype.addAll) {
Set.prototype.addAll = function(items) {
if (!Array.isArray(items)) throw new TypeError('passed item is not an array');
// or (not sure what the real Set.prototype will get sometime)
// if (!Array.isArray(items)) items = [items];
for (let it of items) {
this.add(it);
}
return this;
}
}
If you decided not to extend the prototype, just create a function that you can reuse in your project
function addAll(_set, items) {
// check set and items
for (let it of items) {
_set.add(it);
}
return _set;
}
Upvotes: -1
Reputation: 69
Just post that here for inspiration .. Creating a class that extends Set, and add a addRange method.
class MegaSet extends Set {
constructor(iterable) {
super(iterable);
}
addRange(range) {
for (var elem of range) {
this.add(elem);
}
}
}
const array = [1,2,3,5,5,6];
let mySet = new MegaSet([1,2,3,4]);
mySet.addRange(array);
console.log([...mySet]);
Upvotes: 4
Reputation: 8740
@Fuzzyma, I'll suggest you to use Prototyping of JavaScript to define new method on Set.
Do not use in-built method name defined on Set.
If you still prefer to use the same function name as in-built function name like
add
then the better approach would be to inherit the Set and overrideadd()
method.This is better way to add methods to existing objects without affecting their methods and use our own methods with same name. The charisma of Method overriding, a nice OOP concept.
Here in the below code, I have defined addItems()
on Set.
Try it online at http://rextester.com/LGPQC98007.
var arr = [3, 7, 8, 75, 65, 32, 98, 32, 3];
var array = [100, 3, 200, 98, 65, 300];
// Create a Set
var mySet = new Set(arr);
console.log(mySet);
// Adding items of array to mySet
Set.prototype.addItems = function(array) {
for(var item of array){
this.add(item)
}
}
mySet.addItems(array);
console.log(mySet)
» Output
Set { 3, 7, 8, 75, 65, 32, 98 }
Set { 3, 7, 8, 75, 65, 32, 98, 100, 200, 300 }
Upvotes: -4