Categories
JavaScript Answers

How to get column from a two dimensional array with JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.