用交替的值合并两个数组 [英] Merge two arrays with alternating Values

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

问题描述

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

  let array2 = [a,b ,c,d]; 
让array2 = [1,2];
$ b让结果= [a,1,b,2,c,d]

最好的方法是做什么?

编辑:我期望得到的结果是 [a,1,b,2,你可以迭代数组和构建的最小长度,这样就可以实现数组和构建的最小长度data-lang =jsdata-hide =falsedata-console = truedata-babel =false>

var array1 = [ a,b,c,d],array2 = [1,2],result = [],i,l = Math.min(array1.length,array2.length);对于(i = 0; i <1; 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] || [])。的concat(b)); console.log(result);


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, "c", "d"] 

Whats the best way to do that?

Edit: The outcome I would expect is ["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天全站免登陆