Javascript equivalent of Python's zip function

前端 未结 18 1636
天命终不由人
天命终不由人 2020-11-21 07:40

Is there a javascript equivalent of Python\'s zip function? That is, given multiple arrays of equal lengths create an array of pairs.

For instance, if I have three

18条回答
  •  日久生厌
    2020-11-21 07:51

    The Python has two functions: zip and itertools.zip_longest. Implementation on JS/ES6 is like this:

    Implementation Python`s zip on 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])));
    };
    

    Results:

    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, false, 212 ], [ 3, -378, 323 ], [ 'a', '337', 433 ] ]

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

    []

    Implementation Python`s zip_longest on 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
            )
        );
    };
    

    Results:

    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, 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, 'Is None', 'Is None' ], [ 'a', '337', 'Is None', 'Is None' ] ]

提交回复
热议问题