EN
JavaScript - get column from two dimensional array
0
points
In this article, we would like to show you how to get a column from a two-dimensional array in JavaScript.
1. Looping through elements
In this example, we create a reusable function that loops through each element in the 2D array and returns the columnIndex column.
// ONLINE-RUNNER:browser;
function getColumn(array, columnIndex) {
var result = new Array(array.length);
for (var i = 0; i < array.length; ++i) {
result[i] = array[i][columnIndex];
}
return result;
}
// Usage example
var array = [
['00', '01', '02'],
['10', '11', '12'],
['20', '21', '22'],
];
console.log(getColumn(array, 0)); // [ '00', '10', '20' ]
console.log(getColumn(array, 1)); // [ '01', '11', '21' ]
console.log(getColumn(array, 2)); // [ '02', '12', '22' ]
2. Using array map() method
In this section, we use array map() method to get the columnIndex column from the array.
// ONLINE-RUNNER:browser;
const getColumn = (array, columnIndex) => array.map((element) => element[columnIndex]);
// Usage example
const array = [
['00', '01', '02'],
['10', '11', '12'],
['20', '21', '22'],
];
console.log(getColumn(array, 0)); // [ '00', '10', '20' ]
console.log(getColumn(array, 1)); // [ '01', '11', '21' ]
console.log(getColumn(array, 2)); // [ '02', '12', '22' ]