0

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]]

JackWhiteIII
  • 1,388
  • 2
  • 11
  • 25
Lior Cohen
  • 5,570
  • 2
  • 14
  • 30
  • It's a sad world without functional programming to zip. There's no built-in, but here's a resource that will help you. http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function – lmcphers Jun 17 '15 at 15:05

2 Answers2

0

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]]
TaoPR
  • 5,932
  • 3
  • 25
  • 35
0

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.

Arnauld
  • 5,847
  • 2
  • 15
  • 32