Javascript equivalent of Python's zip function

前端 未结 18 1631
天命终不由人
天命终不由人 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:46

    Along other Python-like functions, pythonic offers a zip function, with the extra benefit of returning a lazy evaluated Iterator, similar to the behaviour of its Python counterpart:

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

    Disclosure I'm author and maintainer of Pythonic

提交回复
热议问题