交替合并两个不同长度的数组,JavaScript

oij*_*djn 0 javascript arrays

我想或者连接两个不同长度的数组。

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);
Run Code Online (Sandbox Code Playgroud)

当运行此代码结果时, ['a', 1, 'b', 2, 'c', 3, 'd', 4]

我想要 ['a', 1, 'b', 2, 'c', 3, 'd', 4,5,6,7,8,9]

const array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const array2 = [1, 2, 3, 4];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);
Run Code Online (Sandbox Code Playgroud)

当运行此代码结果时, ['a', 1, 'b', 2, 'c', 3, 'd', 4,'e',undefined,'f',undefined,'g',undefined]

我想要 ['a', 1, 'b', 2, 'c', 3, 'd', 4,'e','f','g']

有两种情况。

如果数组 1 很短,则数组 2 中的某些值会丢失。

如果数组 1 很长,则将在合并的数组之间插入 undefined。

无论长度如何,如何交替合并两个数组?

当我使用时Swift,使用zip2sequence是一个简单的解决方案。有JavaScript没有类似的?

Bar*_*mar 5

使用for循环而不是reduce,这样您就不会受到任一数组长度的限制。

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const len = Math.max(array1.length, array2.length);
const result = [];
for (let i = 0; i < len; i++) {
  if (array1[i] !== undefined) {
    result.push(array1[i]);
  }
  if (array2[i] !== undefined) {
    result.push(array2[i]);
  }
}
console.log(result);
Run Code Online (Sandbox Code Playgroud)