Understanding 2D Matrices in JavaScript

ยท

3 min read

In JavaScript, handling 2D matrices (also known as 2D arrays) is a common requirement when working with grids, tables, or spatial data. A 2D matrix is essentially an array of arrays, where each inner array represents a row of elements.

Initializing a 2D Matrix

You can declare and initialize a 2D matrix using nested arrays:

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

In this example, matrix[0][0] gives 1, matrix[1][2] gives 6, and so on.

Creating an Empty 2D Matrix

You can dynamically create an empty matrix of given rows and columns:

function createEmptyMatrix(rows, cols) {
    let matrix = new Array(rows);
    for (let i = 0; i < rows; i++) {
        matrix[i] = new Array(cols).fill(0);
    }
    return matrix;
}

let emptyMatrix = createEmptyMatrix(3, 3);
console.log(emptyMatrix);

Output:

[
  [0, 0, 0],
  [0, 0, 0],
  [0, 0, 0]
]

Accessing and Modifying Elements

You can access and modify elements using row and column indices:

matrix[1][2] = 99;  // Changing element at row index 1 and column index 2
console.log(matrix);

Output:

[
  [1, 2, 3],
  [4, 5, 99],
  [7, 8, 9]
]

Iterating Over a 2D Matrix

Row-wise Traversal

for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
        console.log(matrix[i][j]);
    }
}

Column-wise Traversal

for (let j = 0; j < matrix[0].length; j++) {
    for (let i = 0; i < matrix.length; i++) {
        console.log(matrix[i][j]);
    }
}

Common Operations on 2D Matrices

Filling the Matrix

You can fill the entire matrix with a specific value:

matrix.forEach(row => row.fill(1));
console.log(matrix);

Output:

[
  [1, 1, 1],
  [1, 1, 1],
  [1, 1, 1]
]

Transposing a Matrix

Transposing a matrix means converting its rows into columns:

function transposeMatrix(matrix) {
    let rows = matrix.length;
    let cols = matrix[0].length;
    let transposed = createEmptyMatrix(cols, rows);

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            transposed[j][i] = matrix[i][j];
        }
    }
    return transposed;
}

let transposedMatrix = transposeMatrix(matrix);
console.log(transposedMatrix);

Summing Elements

Find the sum of all elements in the matrix:

let sum = matrix.flat().reduce((acc, val) => acc + val, 0);
console.log(sum);

Searching for an Element

You can search for an element and return its position:

function findElement(matrix, target) {
    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] === target) {
                return [i, j];
            }
        }
    }
    return [-1, -1];
}

console.log(findElement(matrix, 99));  // Output: [1, 2]

Advanced Matrix Operations

Rotating a Matrix 90 Degrees

To rotate a matrix clockwise by 90 degrees:

function rotateMatrix(matrix) {
    let transposed = transposeMatrix(matrix);
    return transposed.map(row => row.reverse());
}

console.log(rotateMatrix(matrix));

Checking if Matrix is Symmetric

A symmetric matrix is one where matrix[i][j] === matrix[j][i].

function isSymmetric(matrix) {
    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] !== matrix[j][i]) {
                return false;
            }
        }
    }
    return true;
}

console.log(isSymmetric(matrix));

Practical Applications of 2D Matrices

  • Game Development: Used for grid-based games like chess, tic-tac-toe.

  • Pathfinding Algorithms: Used in applications like GPS, robotics.

  • Image Processing: Represent pixel values in a 2D array.

  • Data Analysis: Store and process tabular data efficiently.

Conclusion

Working with 2D matrices in JavaScript is straightforward but requires careful indexing and iteration. Understanding common operations like initialization, traversal, and manipulation can help in solving complex programming challenges effectively.

Did you find this article valuable?

Support Mikey's Blog by becoming a sponsor. Any amount is appreciated!

ย