Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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]]);
})

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]];
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top