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