What is the most efficient way of merging [1,2] and [7,8] into [[1,7], [2,8]]

前端 未结 4 1758
囚心锁ツ
囚心锁ツ 2021-01-13 15:43

Given 2 arrays [1,2] and [7,8] what is the most efficient way of merging that to form [[1,7], [2,8]]. I know we can do this:

a1 = [1,2], a2 = [7,8], a3=[];
f         


        
4条回答
  •  無奈伤痛
    2021-01-13 16:37

    That is a good question!

    First off, make sure that you assign a1,a2,a3 to the local scope via the var keyword, which it seems you forgot. Otherwise performance can suffer tremendously.

    As for the code-performance comparison. You can test/see the results here:

    zip tests

    pure JavaScript:

    var a1 = [1, 2],
      a2 = [7, 8],
      a3 = [];
    for (var i = 0; i < a1.length; i++) {
      a3.push([a1[i], a2[i]]);
    }
    

    JS/Native methods:

    var a1 = [1, 2],
      a2 = [7, 8],
      a3 = [];
    a3 = a1.map(function(e, i, a) {
      return [e, a2[i]]
    })
    

    Of course there are more possible implementations, but the point is that probably no other implementation can beat a for-loop and straightforward packing, in O(n)-time as kindly pointed out by Travis J.

    Engine/Optimized: V8 JavaScript Engine via Chrome v29

提交回复
热议问题