Merge multiple arrays based on their index using javascript

前端 未结 7 943
清歌不尽
清歌不尽 2020-12-11 16:44

I need to merge two arrays into a single array. I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 17:35

    Well actually JavaScript lacks a .zip() functor which would be very handy for exactly what you are trying to do. Lets invent it;

    Array.prototype.zip = function(a){
     return this.map((e,i) => typeof e === "object" || typeof a[i] === "object" ? [e,a[i]] : e+a[i]);
    };
    
    var arrays = [[1, 2, 3, 4],
                  ["a", "b", "c", "d"],
                  [9, 8, 7, 6],
                  ["z", "y", "x", "w"],
                  [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
                 ],
    result = arrays.reduce((p,c) => p.zip(c));
    console.log(result);

提交回复
热议问题