1

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.

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

For the same length array we can use map function - Nikhil's Answer

I am just providing more information if both array's are of different lengths.

 function mixArray(a, b) {
   if (a.length < b.length) {
     var j = Array(b.length-a.length).fill('');  
     a = a.concat(j);
   }

 return a.map(function(item, index) {
     var tempArr = [];
     if (item !== '') {
       tempArr.push(item);
     }
     if (b[index] !== undefined) {
       tempArr.push(b[index]);
     }
     return tempArr;
  });

}

Inputs

var a = [1, 2, 3, 7, 8, 9];
var b = [20, 10, 30, 5];
console.log(mixArray(a,b));  // [[1, 20], [2, 10], [3, 30], [7, 5], [8], [9]]

var a = [1, 2];
var b = [20, 10, 30, 5];
console.log(mixArray(a,b)); // [[1, 20], [2, 10], [30], [5]]

Hope this helps ! Thanks Demo : https://jsbin.com/dusuna/edit?html,js,console

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.