DEV Community

Cover image for Day 22 of JavaScriptmas - Extract Matrix Column Solution
Sekti Wicaksono
Sekti Wicaksono

Posted on

Day 22 of JavaScriptmas - Extract Matrix Column Solution

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]
]
Enter fullscreen mode Exit fullscreen mode

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]);
}
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo
const extractMatrixColumn = (matrix, index) =>  {
    return matrix.map(({ [index]: value }) => value);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
flyingduck92 profile image
Sekti Wicaksono

Good one mate, you combine .map with destructuring assignment 👍