Using es6 spread to concat multiple arrays

前端 未结 8 1247
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 14:50

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

8条回答
  •  独厮守ぢ
    2021-01-31 15:18

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

提交回复
热议问题