Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will be the functional approach to add an Array(destructured) into Set

I want to add some array (their contents only) in Set. Like:

My array :

var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33];

I want my Set to be : [55, 44, 65, 22, 11, 33]

What I've tried:

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);                          

It adds three array in sets Instead of individual numbers.

So, I also tried doing this: 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);

However, It only adds the first elements of the array into Set.

  • My question is in my second approach why only first element of array gets added in the Set?
  • How can I add all the elements of the array into the set without iterating through every one of array elements and adding them to Set (like using for , map or forEach)? (If it is possible)

NOTE: In my actual problem I do not get all the arrays at once.

like image 574
BlackBeard Avatar asked Dec 05 '25 04:12

BlackBeard


2 Answers

As commented, you can try

var set = new Set(arr1.concat(arr2, [8, 5]))

You can test it here.


However, It only adds the first elements of the array into Set.

If you refer docs, it says, .add takes only 1 argument. So when you do ...[8, 5], it spreads and adds first value and ignores remaining.


In my actual problem I do not get all the arrays at once.

Here, you can convert the set back to array and create new Set:

var set2 = new Set(Array.from(set).concat([8, 5]))

You can check it here


You can also use spread operator like:

var set2 = new Set([...set].concat([8, 5]))

Updated Fiddle to test it, but as a personal preference, I prefer Array.from as its more readable. You can choose any way you like.

like image 171
Rajesh Avatar answered Dec 07 '25 19:12

Rajesh


If you do not wish to create a new set, there is nothing wrong about a loop:

var arr1 = [55, 44, 65];
var arr2 = [22, 11, 33]
var set = new Set();
var setAdd = set.add.bind(set);
arr1.forEach(setAdd);
arr2.forEach(setAdd);
[8, 5].forEach(setAdd);
console.log(Array.from(set)); // StackOverflow snippet console can't print sets yet
// [55, 44, 65, 22, 11, 33, 8, 5]
like image 43
Amadan Avatar answered Dec 07 '25 18:12

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!