javascript – 使用交替值合并两个数组

我想合并2个不同长度的数组:

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

let outcome = ["a",1 ,"b", 2, "c", "d"] 

什么是最好的方法呢?

编辑:我期望的结果是[“a”,1,“b”,2,“c”,“d”]

您可以迭代两个数组的最小长度并构建替代元素,最后推动其余元素.

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);

使用转置算法和随后展平的任意数组数组的解决方案.

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);
翻译自:https://stackoverflow.com/questions/47061160/merge-two-arrays-with-alternating-values

转载注明原文:javascript – 使用交替值合并两个数组