We all know you can do:
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
But how do you make this dynami
Following solution works for me (spread operator in ES6):
let array = ['my','solution','works'];
let newArray = [];
let newArray2 = [];
newArray.push(...array); //adding to same array
newArray2.push([...array]); //adding as child/leaf/sub-array
console.log(newArray);
console.log(newArray2);
You can't do that with spread syntax alone, as spread syntax requires you to know how many arrays you are concatenating in advance. However, you could write the following function:
function concatN(...arguments) {
let accumulator = [];
for(let arg = 0; arg < arguments.length; arg = arg + 1) {
accumulator = [...accumulator, ...arguments[arg]];
}
return accumulator;
}
It probably won't be very efficient, though (repeated use of spread syntax is O(n²)). Using Array.prototype.concat
would be better. You can just do:
[].concat(all, of, your, arrays);