最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin9浏览0评论

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<a1.length; i++) {
  a3.push([a1[i], a2[i]]);
}

I am dealing with a large array. So I want to see if there is a better way.

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<a1.length; i++) {
  a3.push([a1[i], a2[i]]);
}

I am dealing with a large array. So I want to see if there is a better way.

Share Improve this question asked Apr 24, 2012 at 7:15 SubbuSubbu 3273 silver badges6 bronze badges 1
  • 3 AFAIK, you're doing it well :) – sp00m Commented Apr 24, 2012 at 7:17
Add a ment  | 

4 Answers 4

Reset to default 7

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

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 parison. You can test/see the results here:

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

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

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论