合并两个具有交替值的数组 [英] Merge two arrays with alternating values

查看:19
本文介绍了合并两个具有交替值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我期望的结果是 ["a", 1 ,"b", 2, "c", "d"]

最好的方法是什么?

推荐答案

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

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

这篇关于合并两个具有交替值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆