2

I have an array of arrays:

let theArrayOfArrays = [
  [3,7,8],
  [2,0,9],
  [1,7,5]
];

I want to re-map that array of arrays so all of the numbers at the 0 index are one array, at the 1 index another array ...like so:

let theArrayOfArrays = [
  [3,2,1],
  [7,0,7],
  [8,9,5]
];

This is what I'm doing now (seems like there should be a better way).

   //I know all of the sub arrays are the same length 
   //so I just take the first one and make an array of empty arrays:
   let newArr = [];
   theArrayOfArrays[0].map((num, index)=>newArr[index]=[]);

   //now newArr is an array of 3 empty sub arrays
   //I then map though the original array of arrays and fill in newArr
   theArrayOfArrays.map(subArr => subArr.map( (num, index) =>  newArr[index].push(num) ) );
NewToJS
  • 2,011
  • 4
  • 35
  • 62

0 Answers0