Merge two arrays with alternating Values

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

    This can be done rather simply using a splicing function within reduce:

    function splicer(array, element, index) {
        array.splice(index * 2, 0, element);
        return array;
    }
    
    function weave(array1, array2) {
        return array1.reduce(splicer, array2.slice());
    }
    
    let array1 = ["a", "b", "c", "d"];
    let array2 = [1, 2];
    
    let outcome = weave(array1, array2);
    
    console.log(outcome);

提交回复
热议问题