简体   繁体   English

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

[英]How do I easily combine elements from two arrays in Javascript, alternating elements?

I have two arrays in JavaScript, of potentially different lengths: 我在JavaScript中有两个数组,它们的长度可能不同:

var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];

I'd like to combine them into one array: 我想将它们组合成一个数组:

var z = ['a', 'g', 'b', 'h', 'c', 'i', 'j'];

How can I do that in JavaScript? 如何在JavaScript中做到这一点?

I see you answered your question at the same time as asking it. 我看到您在提问的同时回答了您的问题。 That's fine, but it's now clear that you were looking for a solution that leverages a library (eg, lodash) and not necessarily one that teaches you how to build such a procedure. 很好,但是现在很清楚,您正在寻找一种利用库的解决方案(例如lodash),而不一定是教您如何构建这样一个过程的解决方案。 In retrospect, I would've answered this differently, but nevertheless I think you can learn something from this answer. 回想起来,我会以不同的方式回答这个问题,但是我认为您可以从该回答中学到一些东西。


I would recommend calling this something other than zip just because zip is used as name for a procedure that does something quite different from what you're looking for. 我建议将其称为zip以外的名称,因为zip用作过程的名称,该过程与您要查找的内容完全不同。

Here's a simple recursive definition of interleave - 这是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 ] 

And another variation that supports any number of input arrays - 另外一个支持任意数量的输入数组的变体-

 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 ] 

A simple implementation that will stitch the arrays: 一个简单的实现将缝合数组:

 function stitch(x, y) { var arr = []; var length = Math.max(x.length, y.length); for(var i = 0; i < length; i++) { i < x.length && arr.push(x[i]); i < y.length && arr.push(y[i]); } return arr; } var x = ['a', 'b', 'c']; var y = ['g', 'h', 'i', 'j']; console.log(stitch(x, y)); 

tl;dr : z = _.flatten(_.zip(x, y)).filter(element => element) , as long as you don't care about null elements in the original arrays. tl; drz = _.flatten(_.zip(x, y)).filter(element => element) ,只要您不在乎原始数组中的null元素即可。


Some of the libraries providing functional tools, such as Lodash , provide enough mechanics to easily do this. 提供功能工具的某些库(例如Lodash )提供了足够的机制来轻松实现此目的。 For example, you can do this: 例如,您可以这样做:

var z1 = _.zip(x, y);
// z1 is now [["a","g"],["b","h"],["c","i"],[null,"j"]]

var z2 = _.flatten(z1);
// z2 is now ["a","g","b","h","c","i",null,"j"]

var z3 = z2.filter(element => element)
// z3 is now ["a","g","b","h","c","i","j"]

Note that this will only work if the original arrays do not contain any null elements, as they are filtered out by the last step. 请注意,这仅在原始数组不包含任何null元素的情况下才有效,因为最后一步将它们过滤掉了。

This is the functional way to address the problem: 这是解决问题的功能方法:

var x = ['a', 'b', 'c'];
var y = ['g', 'h', 'i', 'j'];

function stitch(x,y) {

var a = x.length > y.length ? x : y;
var b = x.length > y.length ? y : x;

var c = a.map(function (e, i) {
    return b.length<i ? [e, b[i]] : [];
});

return [].concat.apply([],c)
}

Here's a very simple recursive solution: 这是一个非常简单的递归解决方案:

 const interlace = (xxs, ys) => { if (xxs.length === 0) return ys; const [x, ...xs] = xxs; return [x, ...interlace(ys, xs)]; }; const xs = ['a', 'b', 'c']; const ys = ['g', 'h', 'i', 'j']; console.log(JSON.stringify(interlace(xs, ys))); 

In addition, you can easily generalize this algorithm to an arbitrary number of arrays: 另外,您可以轻松地将此算法推广为任意数量的数组:

 const interlace = (...xss) => xss.length > 0 ? interleave(...xss) : []; const interleave = (xxs, ...yss) => { if (xxs.length === 0) return interlace(...yss); const [x, ...xs] = xxs; return [x, ...interleave(...yss, xs)]; }; const xs = ['a', 'b', 'c']; const ys = ['g', 'h', 'i', 'j']; const zs = ['d', 'e', 'f']; console.log(JSON.stringify(interlace())); console.log(JSON.stringify(interlace(xs))); console.log(JSON.stringify(interlace(xs, ys))); console.log(JSON.stringify(interlace(xs, ys, zs))); 

Hope that helps. 希望能有所帮助。

This can be done in regular Javascript. 这可以用常规Javascript完成。 No need for fancy tricks: 无需花哨的技巧:

 function splicer(array, element, index) { array.splice(index * 2, 0, element); return array; } function weave(array1, array2) { return array1.reduce(splicer, array2.slice()); } var x = ['a', 'b', 'c']; var y = ['g', 'h', 'i', 'j']; var z = weave(x, y); console.log(z); 

 var x = ['a', 'b', 'c']; var y = ['g', 'h', 'i', 'j']; var z=[]; if(y.length>=x.length){ for(var i=0;i<x.length;i++){ z.push(x[i]); z.push(y[i]); } while(i<y.length) z.push(y[i++]); }else{ for(var i=0;i<y.length;i++){ z.push(x[i]); z.push(y[i]); } while(i<x.length) z.push(x[i++]); } window.alert(JSON.stringify(z)); // print ["a","g","b","h","c","i","j"] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM