Javascript equivalent of Python's zip function

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

    This shaves a line off Ddi's iterator-based answer:

    function* zip(...toZip) {
      const iterators = toZip.map((arg) => arg[Symbol.iterator]());
      const next = () => toZip = iterators.map((iter) => iter.next());
      while (next().every((item) => !item.done)) {
        yield toZip.map((item) => item.value);
      }
    }
    

提交回复
热议问题