Javascript equivalent of Python's zip function

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

    Modern ES6 example with a generator:

    function *zip (...iterables){
        let iterators = iterables.map(i => i[Symbol.iterator]() )
        while (true) {
            let results = iterators.map(iter => iter.next() )
            if (results.some(res => res.done) ) return
            else yield results.map(res => res.value )
        }
    }
    

    First, we get a list of iterables as iterators. This usually happens transparently, but here we do it explicitly, as we yield step-by-step until one of them is exhausted. We check if any of results (using the .some() method) in the given array is exhausted, and if so, we break the while loop.

提交回复
热议问题