Using es6 spread to concat multiple arrays

前端 未结 8 1234
伪装坚强ぢ
伪装坚强ぢ 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:14

    You could use a recursive function and Array.prototype.concat

    const concatN = (x,...xs) =>
      x === undefined ? [] : x.concat(concatN(...xs))
    
    console.log(concatN([1,2,3], [4,5,6], [7,8,9]))
    // [1,2,3,4,5,6,7,8,9]

    You can do the same thing using reduce and Array.prototype.concat. This is similar to the accepted answer but doesn't senselessly use spread syntax where x.concat(y) is perfectly acceptable (and likely heaps faster) in this case

    const concatN = (...xs) =>
      xs.reduce((x,y) => x.concat(y), [])
    
    console.log(concatN([1,2,3], [4,5,6], [7,8,9]))
    // [1,2,3,4,5,6,7,8,9]

提交回复
热议问题