Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an array of values to a Set

Tags:

javascript

set

People also ask

How do you add values to an array of objects?

The push() function is a built-in array method of JavaScript. It is used to add the objects or elements in the array. This method adds the elements at the end of the array. "Note that any number of elements can be added using the push() method in an array."

Does set work with arrays?

A Set works on objects and primitives and is useful for preventing identical primitives and re-adding the same object instance. Each array is their own object, so you can actually add two different arrays with the same values. Additionally, there's nothing to prevent an object from being changed once in a set.

How do you sum an array of numbers?

To get the sum of an array of numbers:Use the Array. reduce() method to iterate over the array. Set the initial value in the reduce method to 0 . On each iteration, return the sum of the accumulated value and the current number.


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)

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' }

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

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


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

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