Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
danday74 Avatar asked Apr 17 '17 17:04

danday74


2 Answers

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

like image 112
Brian McCutchon Avatar answered Sep 26 '22 06:09

Brian McCutchon


Another option could be:

const nArrays = [    [1, 2, 3, 4, 5],    [6, 7, 8, 9],    [10, 11]  ];  const flattened = [].concat(...nArrays);  console.log(flattened)
like image 35
acontell Avatar answered Sep 24 '22 06:09

acontell