dorien dorien - 2 months ago 5
Javascript Question

Forming an new javascript array by combining two columns of another array

I am trying to form a new array in javascript that consists of two 1 dimentional arrays (of the same length).

var A = [1,2,3];
var B = [20, 10, 30];


and I want to create C:

C = [[1,20],[2,10],[3,30]];


This seems like a fairly simple problem. I am wondering if there is a function I can use for this (to avoid loops). Perhaps something with array.from or map? I am having some trouble figuring out how that would work exactly.

Answer

You can try following

 var A = [1, 2, 3];
 var B = [20, 10, 30];

 var C = A.map(function(item, index) {
   return [item, B[index]]

 });

 console.log(C);

Comments