Merge two arrays with alternating Values

前端 未结 9 2149
南笙
南笙 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:15

    You could iterate the min length of both array and build alternate elements and at the end push the rest.

    var array1 = ["a", "b", "c", "d"],
        array2 = [1, 2],
        result = [],
        i, l = Math.min(array1.length, array2.length);
        
    for (i = 0; i < l; i++) {
        result.push(array1[i], array2[i]);
    }
    result.push(...array1.slice(l), ...array2.slice(l));
    
    console.log(result);

    Solution for an arbitrary count of arrays with a transposing algorithm and later flattening.

    var array1 = ["a", "b", "c", "d"],
        array2 = [1, 2],
        result = [array1, array2]
            .reduce((r, a) => (a.forEach((a, i) => (r[i] = r[i] || []).push(a)), r), [])
            .reduce((a, b) => a.concat(b));
        
    console.log(result);

提交回复
热议问题