DEV Community

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

Posted on

2 1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

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 👍

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs