How to add an array of values to a Set
JavascriptSetJavascript Problem Overview
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
Javascript Solutions
Solution 1 - Javascript
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)
Solution 2 - Javascript
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' }
Solution 3 - Javascript
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);
Solution 4 - Javascript
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][1] [1]: https://jsfiddle.net/clayperez/yjkxh9d8/9/
Solution 5 - Javascript
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);
Solution 6 - Javascript
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])]))]);
Solution 7 - Javascript
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]);
Solution 8 - Javascript
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;
}
Solution 9 - Javascript
@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 override add()
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 }