Skip to content Skip to sidebar Skip to footer

What Is The Most Efficient Way Of Merging [1,2] And [7,8] Into [[1,7], [2,8]]

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=[]; for (var i=0; i

Solution 1:

There is no way to do this faster than O(n) because every element must be touched once.

Solution 2:

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

Solution 3:

You are basically searching for a function identical to Python's zip function, so check out the answers to an older SO question:

Javascript equivalent of Python's zip function

Solution 4:

Nope, that's about as efficient as it gets. It's running in O(n) time. Really not much more you could ask. If there's anything you could optimize, it would be transforming a1 into a map, but that's optimization for memory, and it sounds like you want to speed things up intstead.

Post a Comment for "What Is The Most Efficient Way Of Merging [1,2] And [7,8] Into [[1,7], [2,8]]"