Get column from a two dimensional array
How can I retrieve a column from a 2-dimensional array and not a single entry? I'm doing this because I want to search for a string in one of the columns only so if there is another way to accomplish this please tell me.
I'm using the array defined this way:
var array=[];
At the end the size of this array is 20(col)x3(rows) and I need to read the first row and check the existence of some phrase in it.
Solution 1:
Taking a column is easy with the map function.
// a two-dimensional array
var two_d = [[1,2,3],[4,5,6],[7,8,9]];
// take the third column
var col3 = two_d.map(function(value,index) { return value[2]; });
Why bother with the slice at all? Just filter the matrix to find the rows of interest.
var interesting = two_d.filter(function(value,index) {return value[1]==5;});
// interesting is now [[4,5,6]]
Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.
Solution 2:
Use Array.prototype.map()
with an arrow function:
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));
Note: Array.prototype.map()
and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.