Javascript ES6 - map multiple arrays

后端 未结 3 1687
甜味超标
甜味超标 2021-01-07 22:23

Is there a feature in JavaScript 6 that allows to map over multiple arrays ?

Something like a zipper :

 var myFn = function (a, b) { console.log(a, b         


        
相关标签:
3条回答
  • 2021-01-07 22:54

    You could also use reduce to get the desired outcome:

    var arr1 = ['a', 'b', 'c'];
    var arr2 = [1, 2, 3];
    
    arr1.reduce((acc, current, index) => {
       console.log(current, arr2[index])
       return [...acc, current, arr2[index]]
    }, [])
    
    // a 1
    // b 2
    // c 3
    // returns ["a", 1, "b", 2, "c", 3]
    
    0 讨论(0)
  • 2021-01-07 23:12

    As the other answer points out, this is commonly known as a zip. It can be implemented as:

    let zipped = arr1.map((x, i) => [x, arr2[i]]);
    

    Or as a function, basically:

    let zip = (a1, a2) => a1.map((x, i) => [x, a2[i]]); 
    

    Which would let you do:

    zip(["a","b","c"], [1,2,3]); // ["a", 1], ["b", 2], ["c", 3]
    
    0 讨论(0)
  • 2021-01-07 23:18

    Unfortunately, no. What you are looking for is commonly called zip or zipWith. See lodash's implementation for a reference: https://lodash.com/docs#zipWith

    0 讨论(0)
提交回复
热议问题