Javascript equivalent of Python's zip function

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

    You could reduce the array of arrays and map new array by taking the result of the index of the inner array.

    var array1 = [1, 2, 3],
        array2 = ['a','b','c'],
        array3 = [4, 5, 6],
        array = [array1, array2, array3],
        transposed = array.reduce((r, a) => a.map((v, i) => (r[i] || []).concat(v)), []);
    
    console.log(transposed);

提交回复
热议问题