Using es6 spread to concat multiple arrays

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

    We can resolve using es6 following way

    function mergeTwo(arr1, arr2) {
      let result = [...arr1, ...arr2];
      return result.sort((a,b) => a-b);
    }
    
    0 讨论(0)
  • 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]

    0 讨论(0)
  • 2021-01-31 15:15

    You can use spread element within for..of loop to concatenate array values to a single array

    let arr1 = [1,2,3];
    let arr2 = [3,4,5];
    let arr3 = [];
    
    for (let arr of [arr1, arr2 /* , arrN */]) arr3.push(...arr);
    
    console.log(arr3);

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-31 15:21

    Another option could be:

    const nArrays = [
      [1, 2, 3, 4, 5],
      [6, 7, 8, 9],
      [10, 11]
    ];
    const flattened = [].concat(...nArrays);
    console.log(flattened)

    0 讨论(0)
  • 2021-01-31 15:25

    let fruits = ["apples", "bananas", "pears"];
    let vegetables = ["corn", "potatoes", "carrots"];
    
    let produce = [...fruits, ...vegetables];
    
    
    console.log(produce);

    0 讨论(0)
提交回复
热议问题