0

How does one loop through sub arrays of a parent array but iterate over one index per sub array.

I know the solution I want involves at least iterating over a 2D array but I currently know how to print all elements of sub arrays in a parent array

For example say I have const array = [[1, 2, 3], ['a', 'b', 'c'], ['@', '#', '%']];

How do I get const result = [[1, 'a', '@'], [2, 'b', '#'], [3, 'c', '%']; ?

  • This operation is called [Convolution](https://en.wikipedia.org/wiki/Convolution_(computer_science)), and to search for the right answer you should search for "javascript zip array", which would bring you to [this question](https://stackoverflow.com/q/4856717/8557739). – T Tse Jun 21 '19 at 05:49
  • `array[0].map((_, i) => array.map(row => row[i]))` – adiga Jun 21 '19 at 05:54
  • Wow! thanks, sorry for asking a duplicate question, I did not know there was an actual word for what I was describing ie transposing sub arrays in an array. I think I have enough clues and answers to play with and understand. Thanks again everyone – Okezie Frank Obiedere Jun 21 '19 at 06:44

1 Answers1

1

Here is what i got, See if you like it.

const array = [[1, 2, 3], ['a', 'b', 'c'], ['@', '#', '%']];
var res =array.map((a,i)=>{ 
return a.map((x, index)=>{
  return array[index][i]
 });
});
console.log(res)
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31