Sometimes, we want to get column from a two dimensional array with JavaScript.
In this article, we’ll look at how to get column from a two dimensional array with JavaScript.
How to get column from a two dimensional array with JavaScript?
To get column from a two dimensional array with JavaScript, we can use the array map method.
For instance, we write
const arrayColumn = (arr, n) => arr.map((x) => x[n]);
const twoDimensionalArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(arrayColumn(twoDimensionalArray, 0));
to define the arrayColumn function that return an array with the items from column n in the 2D array arr.
We call map with a callback that returns the item at index n of each array in arr.
Then we call arrayColumn with twoDimensionalArray and 0 to get [1, 4, 7].
Conclusion
To get column from a two dimensional array with JavaScript, we can use the array map method.