0

How can I merge two javascript array, for example: [0,1,2,3,4] and [5,6,7,8,9]

when merged, result in:

[[0,5], [1,6], [2,7], [3,8], [4,9]]

the most optimized way possible, even using the "map" or specific methods.

edi9999
  • 19,701
  • 13
  • 88
  • 127
  • 2
    @edi9999 it looks simple and basic for you and me. but there are people out there who have just started with these technologies, we should understand them, SO made for all, beginner and expert! – Rashmin Javiya May 12 '14 at 05:55
  • 1
    To add on `@thefourtheye` comment, have a look [at the **answer**. If it helps](http://stackoverflow.com/a/10284006/769678). – Shubh May 12 '14 at 05:59

3 Answers3

3

Try something like:

var a = [0,1,2,3,4],
    b = [5,6,7,8,9];
Array.prototype.zip = function (arr) {
    return this.map(function (e, i) {
        return [e, arr[i]];
    })
};

a.zip(b) would give [[0,5], [1,6], [2,7], [3,8], [4,9]]

DEMO

tewathia
  • 6,890
  • 3
  • 22
  • 27
1

Try this

var arrFirst = [0,1,2,3,4];
var arrSecond = [5,6,7,8,9];

var arrFinal = [];

$(arrFirst).each(function(index, val){
    arrFinal.push([arrFirst[index], arrSecond[index]]);
})
Rashmin Javiya
  • 5,173
  • 3
  • 27
  • 49
0

The map function constructs a new array, where each key is determined by the callback function you write

arrFirst.map(function(value,index){
        return [arrFirst[index],arrSecond[index]];
})
edi9999
  • 19,701
  • 13
  • 88
  • 127