Using es6 spread to concat multiple arrays
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 dynamic to concat N arrays?
Solution 1:
One option is to use reduce
:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);
Of course, this is a slow solution (quadratic time). Alternatively, if you can use Lodash, _.flatten
does exactly what you want, and does it more efficiently (linear time).
EDIT
Or, adapted from Xotic750's comment below,
[].concat(...arrs);
Which should be efficient (linear time).
Solution 2:
Another option could be:
const nArrays = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9],
[10, 11]
];
const flattened = [].concat(...nArrays);
console.log(flattened)
Solution 3:
let fruits = ["apples", "bananas", "pears"];
let vegetables = ["corn", "potatoes", "carrots"];
let produce = [...fruits, ...vegetables];
console.log(produce);
Solution 4:
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);
Solution 5:
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);