Array columns into new array

A simple but useful question!

You can use the map() method to transform an array of arrays (i.e., a 2D array) into a new array with the columns of the original array.

Here's an example:

const originalArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

const columns = originalArray.map((row) => row);

console.log(columns); // Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

In this example, map() is called on the original array, and each element of the original array (which is an array itself) is passed to the callback function. The callback function simply returns the element itself, which is the column of the original array.

Alternatively, you can use Array.prototype.reduce() to achieve the same result:

const originalArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

const columns = originalArray.reduce((acc, row) => {
  acc.push(row);
  return acc;
}, []);

console.log(columns); // Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

In this example, reduce() is called on the original array, and the initial value is an empty array []. The callback function is called for each element of the original array, and it pushes the element (which is an array itself) to the accumulator array. The final result is the array of columns.