2

I have a two array

var arr1 = [0,1,2,3,4]
var arr2 = [23,32,11,35,15]

how do i get this ?

var result = [[0,23],[1,32],[2,11],[3,35],[4,15]]
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Saurabh
  • 1,592
  • 2
  • 14
  • 30

2 Answers2

1

In simple terms, do the following:

  1. Compare the lengths to be equal.
  2. Combine the arrays and create a new one.

var arr1 = [0,1,2,3,4];
var arr2 = [23,32,11,35,15];
var result = [];

if (arr1.length === arr2.length)
  result = arr1.map(function (cur, idx) {
    return [cur, arr2[idx]];
  });
console.log(result);

More shorter version using ES 6 arrow function:

var arr1 = [0,1,2,3,4];
var arr2 = [23,32,11,35,15];
var result = [];

if (arr1.length === arr2.length)
  result = arr1.map((cur, idx) => [cur, arr2[idx]]);
console.log(result);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

Assuming that the two input arrays are the same length:

var result = arr1.map((item, idx) => [item, arr2[idx]])
Steve Archer
  • 641
  • 4
  • 10