如何在Javascript中轻松组合来自两个数组的元素,交替元素?

And*_*ier 0 javascript arrays functional-programming

我在JavaScript中有两个数组,它们的长度可能不同:

var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];
Run Code Online (Sandbox Code Playgroud)

我想将它们组合成一个数组:

var z = ['a', 'g', 'b', 'h', 'c', 'i', 'j'];
Run Code Online (Sandbox Code Playgroud)

如何在JavaScript中做到这一点?

Tha*_*you 6

我看到您在提问的同时回答了您的问题。很好,但是现在很明显,您正在寻找一种利用库的解决方案(例如lodash),而不一定是教您如何构建这样一个过程的解决方案。回想起来,我会以不同的方式回答这个问题,但是我认为您可以从该回答中学到一些东西。


我建议将其称为“其他”,zip这不仅仅是因为它zip被用作过程的名称,该过程的功能与您所寻找的完全不同。

这是一个简单的递归定义interleave-

const interleave = ([ x, ...xs ], ys = []) =>
  x === undefined
    ? ys                             // base: no x
    : [ x, ...interleave (ys, xs) ]  // inductive: some x

const xs = [ 'a', 'b', 'c' ]
  
const ys = [ 'g', 'h', 'i', 'j' ]

console .log (interleave (xs, ys))
// [ a, g, b, h, c, i, j ]
Run Code Online (Sandbox Code Playgroud)

另外一个支持任意数量的输入数组的变体-

const interleave = ([ x, ...xs ], ...rest) =>
  x === undefined
    ? rest.length === 0
      ? []                                // base: no x, no rest
      : interleave (...rest)              // inductive: no x, some rest
    : [ x, ...interleave (...rest, xs) ]  // inductive: some x, some rest

const ws = [ '0', '1', '2', '3' ]

const xs = [ 'a', 'b', 'c' ]

const ys = [ 'd', 'e', 'f' ]

const zs = [ 'g', 'h', 'i', 'j' ]

console .log (interleave (ws, xs, ys, zs))
// [ 0, a, d, g, 1, b, e, h, 2, c, f, i, 3, j ]
Run Code Online (Sandbox Code Playgroud)