javascript中是否有类似于Python的zip函数?也就是说,给定多个相等长度的数组,创建一个由对组成的数组。

例如,如果我有三个这样的数组:

var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
var array3 = [4, 5, 6];

输出数组应该是:

var outputArray = [[1,'a',4], [2,'b',5], [3,'c',6]]

当前回答

这是我的解决方案

let zip = (a, b) => (a.length < b.length
  ? a.map((e, i) => [e, b[i]])
  : b.map((e, i) => [a[i], e]))

其他回答

查看下划线库。

Underscore提供了超过100个函数,这些函数既支持你最喜欢的日常函数帮助:映射、过滤器、调用——也支持更专业的功能:函数绑定、javascript模板、创建快速索引、深度等式测试等等。

-说说制作它的人

我最近开始专门为zip()函数使用它,它给我留下了很好的第一印象。我使用jQuery和CoffeeScript,它只是完美地与他们。下划线就在他们离开的地方,到目前为止,它还没有让我失望。哦,顺便说一下,它只缩小了3kb。

看看吧:

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
// returns [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

这将从Ddi基于迭代器的答案中删除一行:

function* zip(...toZip) {
  const iterators = toZip.map((arg) => arg[Symbol.iterator]());
  const next = () => toZip = iterators.map((iter) => iter.next());
  while (next().every((item) => !item.done)) {
    yield toZip.map((item) => item.value);
  }
}

我不是一个javascript的人,但我觉得这些答案是试图找到最可爱和最聪明的解决方案使用数组。这是很好的,但对于像我这样不每天使用javascript的人来说,这里有一些可能更可读的替代方案。

也许有一种方法可以避免一些可爱而聪明的代码:

function zip(a,b){
    // pre-allocate an array to hold the results 
    rval=Array(Math.max(a.length, b.length));
    for(i=0; i<rval.length; i++){ 
        rval[i]=[a[i],b[i]] 
    }
    return rval
}

如果你喜欢生成器:

function* _zip(a,b){
    len = Math.max(a.length, b.length) // handle different sized arrays
    for(i=0; i<len; i++) { yield [a[i],b[i]] }
}

或者如果你真的想使用Array.map:

function map(a,b){
    x = a.length > b.length ? a : b // call map on the biggest array
    return x.map((_,i)=>[a[i],b[i]])
}

就像我说的,我不是一个日常使用javascript的人,所以这些不是最优雅的解决方案,但它们对我来说是可读的。

这是我的解决方案

let zip = (a, b) => (a.length < b.length
  ? a.map((e, i) => [e, b[i]])
  : b.map((e, i) => [a[i], e]))

python zip函数的生成器方法。

function* zip(...arrs){
  for(let i = 0; i < arrs[0].length; i++){
    a = arrs.map(e=>e[i])
    if(a.indexOf(undefined) == -1 ){yield a }else{return undefined;}
  }
}
// use as multiple iterators
for( let [a,b,c] of zip([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['hi', 'hello', 'howdy', 'how are you']) )
  console.log(a,b,c)

// creating new array with the combined arrays
let outputArr = []
for( let arr of zip([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['hi', 'hello', 'howdy', 'how are you']) )
  outputArr.push(arr)