Merge two arrays with alternating Values

前端 未结 9 2230
南笙
南笙 2020-12-03 14:19

i would like to merge 2 arrays with a different length:

let array2 = [\"a\", \"b\", \"c\", \"d\"];
let array2 = [1, 2];

let outcome = [\"a\",1 ,\"b\", 2, \"         


        
9条回答
  •  孤街浪徒
    2020-12-03 15:05

    Here's a modern solution that takes any number of arrays:

    const braidArrays = (...arrays) => {
      const braided = [];
      for (let i = 0; i < Math.max(...arrays.map(a => a.length)); i++) {
        arrays.forEach((array) => {
          if (array[i] !== undefined) braided.push(array[i]);
        });
      }
      return braided;
    };
    

    Note that you could change Math.max to Math.min to only include up to the shortest array.

    Here's a sample I/O:

    braidArrays(['a','b','c','d'], [1,2,3], [99,98,97,96,95]);
    // ['a', 1, 99, 'b', 2, 98, 'c', 3, 97, 'd', 96, 95]
    

提交回复
热议问题