Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get all columns as an array from a 2d array which is a rectangle

Q: What do I mean by saying rectangle?
A: [[1,2,3],[1,2,3]] Inner arrays have more elements.

Example:
Input: [[1,2,3,4],[1,2,3,4],[1,2,3,4]]
Desired Output: [[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
Output: [[1,1,1],[2,2,2],[3,3,3]]

The reason of the problem: Main array has less elements, so, when I loop over it, as expected it will return an array with its own length. Shown in the example above.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what I tried with an arbitrary example.

 const arr = [
      [1, 2, 3],
      [1, 2, 3],
    ];

    const get_collum = (arr, i) => arr.map((el) => el[i]);
    const collums = arr.map((_, i, arr) => get_collum(arr, i));

    console.log(collums);

** I know map method returns an array with the same length as main array.
** I also know this is a nested loop.

Thanks for the help.

>Solution :

Assuming "rectangle" implies each sub-array is of equal length:

array[0].map((_, i) => {
  return array.map((el, _) => {
    return el[i];
  });
});

Or, for short:

array[0].map((_, i) => array.map((el, _) => el[i]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading