javascript 2D array from 2 1D array

202 Views Asked by At

I would like to know if there is a builtin function of 2D array building from 2 1D arrays. Of course I can build such function my self but I wonder if there is already array manipulation library.

Example:

input: [1,3,5] and [2,4,6] => [[1,2], [3,4], [5,6]]

2

There are 2 best solutions below

0
On BEST ANSWER

You're looking for a "zip" function

With Underscore.js, zipping arrays made easy

http://underscorejs.org/#zip

var A = [1,3,5];
var B = [2,4,6];
var zipped = _.zip(A,B); // => [[1,2], [3,4], [5,6]]
0
On

Using native JS functions, this is the shortest I can think of right now:

var a = [ 1, 3, 5 ],
    b = [ 2, 4, 6 ],
    c = [];

a.map(function(v, i) { c[i] = [v, b[i]]; });

It does include a short user-defined function, but map allows to significantly simplify the task.

Note that either a or b could be used as the destination array just as well if you don't mind losing their content.