'Array Extend without custom method?
Is it possible to use Array.push to add multiple values from a list? For example, currently what I'm having to do is:
Array.prototype.extend = function(arr) {
for (let elem of arr) {
this.push(elem);
}
}
let x = [1,2,3];
let y = [4,5,6];
let z = [7,8,9];
x.push(y);
x.extend(z)
console.log(x);
Or, is there some way to pass the array as a single argument to the push method, or perhaps there's another Array method entirely that does this instead?
Solution 1:[1]
you can spread the array element like this
const x = [1,2,3];
const y = [4,5,6];
const z = [7,8,9];
x.push(...y);
x.push(...z)
console.log(x);
Solution 2:[2]
You can push multiple arguments to Array.prototype.push and they'll all be pushed to our result array, so we can "convert" our array into multiple arguments using the ES6 spread syntax.
let x = [1,2,3];
let y = [4,5,6];
x.push(...y);
console.log(x);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmed Tarek |
| Solution 2 |
