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.
In this example, we create a reusable function that loops through each element in the 2D array and returns the columnIndex
column.
xxxxxxxxxx
1
function getColumn(array, columnIndex) {
2
var result = new Array(array.length);
3
for (var i = 0; i < array.length; ++i) {
4
result[i] = array[i][columnIndex];
5
}
6
return result;
7
}
8
9
10
// Usage example
11
12
var array = [
13
['00', '01', '02'],
14
['10', '11', '12'],
15
['20', '21', '22'],
16
];
17
18
console.log(getColumn(array, 0)); // [ '00', '10', '20' ]
19
console.log(getColumn(array, 1)); // [ '01', '11', '21' ]
20
console.log(getColumn(array, 2)); // [ '02', '12', '22' ]
In this section, we use array map()
method to get the columnIndex
column from the array
.
xxxxxxxxxx
1
const getColumn = (array, columnIndex) => array.map((element) => element[columnIndex]);
2
3
4
// Usage example
5
6
const array = [
7
['00', '01', '02'],
8
['10', '11', '12'],
9
['20', '21', '22'],
10
];
11
12
console.log(getColumn(array, 0)); // [ '00', '10', '20' ]
13
console.log(getColumn(array, 1)); // [ '01', '11', '21' ]
14
console.log(getColumn(array, 2)); // [ '02', '12', '22' ]