Day 22 Challenge is to extract the specific column from a matrix (list of array).
For example, a matrix with [[1, 1, 1, 2], [0, 5, 0, 4], [2, 1, 3, 6]]
which is has 3 index with 4 values/columns on each array.
If I draw it will be like this
[
[1, 1, 1, 2],
[0, 5, 0, 4],
[2, 1, 3, 6]
]
Since this is list of array, if I want to extract ONLY the SECOND column (in this case the THIRD value because an array index always start at 0
index) that will give me an output [1, 0, 3]
, I will use .map
.
The way it works is, by looping the matrix
using .map
, it will return each array that I called it as element
, and return the value of each column
from the array using element[column]
.
This is the JavaScript solution
function extractMatrixColumn(matrix, column) {
return matrix.map(element => element[column]);
}
The test case
const matrix = [[1, 1, 1, 2], [0, 5, 0, 4], [2, 1, 3, 6]];
const column = 2;
extractMatrixColumn(matrix, column); // [1, 0, 3]
Top comments (2)
Good one mate, you combine
.map
with destructuring assignment 👍