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."
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With