Javascript equivalent of Python's zip function

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

    A variation of the lazy generator solution:

    function* iter(it) {
        yield* it;
    }
    
    function* zip(...its) {
        its = its.map(iter);
        while (true) {
            let rs = its.map(it => it.next());
            if (rs.some(r => r.done))
                return;
            yield rs.map(r => r.value);
        }
    }
    
    for (let r of zip([1,2,3], [4,5,6,7], [8,9,0,11,22]))
        console.log(r.join())
    
    // the only change for "longest" is some -> every
    
    function* zipLongest(...its) {
        its = its.map(iter);
        while (true) {
            let rs = its.map(it => it.next());
            if (rs.every(r => r.done))
                return;
            yield rs.map(r => r.value);
        }
    }
    
    for (let r of zipLongest([1,2,3], [4,5,6,7], [8,9,0,11,22]))
        console.log(r.join())

    And this is the python's classic "n-group" idiom zip(*[iter(a)]*n):

    triples = [...zip(...Array(3).fill(iter(a)))]
    

提交回复
热议问题