[英]javascript 2D array from 2 1D array
I would like to know if there is a builtin function of 2D array building from 2 1D arrays. 我想知道是否有从2个1D数组构建2D数组的内置函数。 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]] 输入:[1,3,5]和[2,4,6] => [[1,2,3,4,5,6]
You're looking for a "zip" function 您正在寻找“ zip”功能
With Underscore.js, zipping arrays made easy 使用Underscore.js,压缩数组变得容易
http://underscorejs.org/#zip 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]]
Using native JS functions, this is the shortest I can think of right now: 使用本机JS函数,这是我现在能想到的最短的代码:
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. 它确实包括一个简短的用户定义函数,但是map可以显着简化任务。
Note that either a or b could be used as the destination array just as well if you don't mind losing their content. 请注意,如果您不介意丢失其内容,则也可以将a或b用作目标数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.