mhmtcgrkc
mhmtcgrkc

Reputation: 13

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 fewer elements, so, when I loop over it, as expected it will return an array with its own length. Shown in the example above.

This is what I tried with an arbitrary example.

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

    const get_column = (arr, i) => arr.map((el) => el[i]);
    const columns = arr.map((_, i, arr) => get_column(arr, i));

    console.log(columns);

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.

Upvotes: 0

Views: 44

Answers (2)

elyees
elyees

Reputation: 11

const inputArray = [

[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]  

];

const transposeArray = (array) => {

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

const outputArray = transposeArray(inputArray);
console.log(outputArray);

The transposed array is stored in the outputArray variable.

Output.

[
  [1, 1, 1],
  [2, 2, 2],
  [3, 3, 3],
  [4, 4, 4]
]

Upvotes: 0

Dennis Hackethal
Dennis Hackethal

Reputation: 14295

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

Upvotes: 0

Related Questions