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]]

当前回答

Python有两个压缩序列的函数:zip和itertools.zip_longest。Javascript中相同功能的实现如下所示:

Python的zip在JS/ES6上的实现

const zip = (...arrays) => {
    const length = Math.min(...arrays.map(arr => arr.length));
    return Array.from({ length }, (value, index) => arrays.map((array => array[index])));
};

结果:

console.log(zip(
    [1, 2, 3, 'a'],
    [667, false, -378, '337'],
    [111],
    [11, 221]
));

[[1, 667, 111, 11]

console.log(zip(
    [1, 2, 3, 'a'],
    [667, false, -378, '337'],
    [111, 212, 323, 433, '1111']
));

[[1、667、111],[2,假的,212年],[3、-378、323],[' a ', “337”,433]]

console.log(zip(
    [1, 2, 3, 'a'],
    [667, false, -378, '337'],
    [111],
    []
));

[]

Python的zip_longest在JS/ES6上的实现

(https://docs.python.org/3.5/library/itertools.html?highlight=zip_longest # itertools.zip_longest)

const zipLongest = (placeholder = undefined, ...arrays) => {
    const length = Math.max(...arrays.map(arr => arr.length));
    return Array.from(
        { length }, (value, index) => arrays.map(
            array => array.length - 1 >= index ? array[index] : placeholder
        )
    );
};

结果:

console.log(zipLongest(
    undefined,
    [1, 2, 3, 'a'],
    [667, false, -378, '337'],
    [111],
    []
));

[[1,667, 111, undefined], [2, false, undefined, undefined], [3, -378, undefined, undefined], ['a', '337', undefined, 未定义

console.log(zipLongest(
    null,
    [1, 2, 3, 'a'],
    [667, false, -378, '337'],
    [111],
    []
));

[[1, 667, 111, null], [2, false, null, null], [3, -378, Null, Null], ['a', '337', Null, Null]]

console.log(zipLongest(
    'Is None',
    [1, 2, 3, 'a'],
    [667, false, -378, '337'],
    [111],
    []
));

[[1,667, 111, 'Is None'], [2, false, 'Is None', 'Is None'], [3, -378,“没有”,“没有 ' ], [ ' ”、“337”、“没有”、“ 没有']]

其他回答

与其他类似Python的函数一样,pythonic提供了一个zip函数,其额外的好处是返回一个惰性求值迭代器,类似于Python对应的行为:

import {zip, zipLongest} from 'pythonic';

const arr1 = ['a', 'b'];
const arr2 = ['c', 'd', 'e'];
for (const [first, second] of zip(arr1, arr2))
    console.log(`first: ${first}, second: ${second}`);
// first: a, second: c
// first: b, second: d

for (const [first, second] of zipLongest(arr1, arr2))
    console.log(`first: ${first}, second: ${second}`);
// first: a, second: c
// first: b, second: d
// first: undefined, second: e

// unzip
const [arrayFirst, arraySecond] = [...zip(...zip(arr1, arr2))];

我是Pythonic的作者和维护者

我不是一个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的人,所以这些不是最优雅的解决方案,但它们对我来说是可读的。

查看下划线库。

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]]

1. 模块:zip-array

我发现了一个npm模块,可以用作python zip的javascript版本:

zip-array——javascript中类似于Python的zip函数。将每个数组的值合并在一起。

https://www.npmjs.com/package/zip-array

2. Tensorflow.js中的tf.data.zip()

tensorflow .js用户的另一个替代选择是:如果你需要python中的zip函数来处理Javascript中的tensorflow数据集,你可以使用tensorflow .js中的tf.data.zip()。

Tensorflow.js中的tf.data.zip()文档在这里

原始答案(见下文更新)

我修改了flm的漂亮答案,以获取任意数量的数组:

函数* zip(数组,I = 0) { 虽然(我< Math.min(…arrays.map(({长度})= >长度))){ 收益率数组。Map ((arr, j) => arr[j <数组。长度- 1 ?I: i++]) } }

更新后的答案

正如Tom Pohl所指出的,这个函数不能处理数组中有假值的数组。下面是一个更新/改进的版本,可以处理任何类型和长度不等的数组:

函数* zip(数组,I = 0) { 虽然(我< Math.min(…arrays.map (arr = > arr.length))) { 收益率数组。Map ((arr, j) => arr[j <数组。长度- 1 ?I: i++]) } } Const arr1 = [false,0,1,2] Const arr2 = [100,null,99,98,97] Const arr3 = [7,8,undefined,"monkey","banana"] console.log(…zip ([arr1、arr2 arr3)))