I have a scenario where I want to add the contents of multiple arrays into a Set. For example:
Arrays to combine :
var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33];
The desired Set should look like this: [55, 44, 65, 22, 11, 33]
This is what I attempted:
var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33]
var set = new Set();
set.add(arr1)
set.add(arr2)
set.add([8, 5])
console.log(set);
However, all three arrays are added as sets instead of individual numbers.
So, I tried another approach which can be found here: JSFiddle
var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33]
var set = new Set();
set.add(...arr1)
set.add(...arr2)
set.add(...[8, 5])
console.log(set);
Unfortunately, only the first elements of each array get added to the Set.
- Why does only the first element of each array get added in my second approach?
- Is there a way to add all elements of an array into a set without iterating through every single element and adding them individually (like using
for
,map
, orforEach
)? (If possible)
NOTE: In my actual situation, I do not receive all the arrays at once.