Print Boundary Elements of a Matrix in JavaScript

Matrixes are basic data structures that are frequently used to represent grids or tables of numbers. Gathering and showing the elements that are positioned along a matrix’s edges is the process of printing the matrix’s boundary elements.

There are several approaches in JavaScript to print the boundary elements of a matrix which are as follows:

Table of Content

  • Using brute force
  • Using for loop
  • Using array methods

Using brute force

This method iterates through the entire matrix and checks if the current element is on the first or last row/column. If it is, it prints the element.

Example: “This function prints boundary elements of a 2D matrix, iterating through rows and columns to exclude interior elements. It demonstrates boundary printing with a sample matrix.”

Javascript
function printBoundary(matrix) {
    const rows = matrix
        .length;
    if (rows === 0) return;
    const cols = matrix[0]
        .length;

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {

            if (i === 0
                ||
                j === 0
                ||
                i === rows - 1
                ||
                j === cols - 1) {
                console.log(matrix[i][j]);
            }
        }
    }
}


const matrix = [
    [1, 2]

];

printBoundary(matrix);

Output
1
2

Using for loop

This method efficiently prints the boundary items without additional checks by iterating through the first and last rows and columns using for loop.

Example:“This function efficiently prints boundary elements of a 2D matrix, showcasing optimized printing steps and providing a sample matrix for demonstration.”

Javascript
function printBoundary(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;

    if (rows === 0 || cols === 0) {
        return; // Empty matrix
    }

    // Print first row
    for (let i = 0; i < cols; i++) {
        console.log(matrix[0][i]);
    }

    // Print last column (excluding corners)
    for (let i = 1; i < rows; i++) {
        console.log(matrix[i][cols - 1]);
    }

    // Print last row (excluding the first element 
    // which has already been printed)
    if (rows > 1) {
        for (let i = cols - 2; i >= 0; i--) {
            console.log(matrix[rows - 1][i]);
        }
    }

    // Print first column (excluding corners and the last 
    // element which has already been printed)
    if (cols > 1) {
        for (let i = rows - 2; i > 0; i--) {
            console.log(matrix[i][0]);
        }
    }
}
const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

printBoundary(matrix);

Output
1
2
3
6
9
8
7
4

Using array methods

The code utilizes the `reduce()` method to iterate over each row of the matrix, extracting boundary elements based on their positions. It concatenates the elements into an array, effectively forming the boundary elements. The `forEach()` method is then used to print each boundary element. Overall, this approach demonstrates how array methods can be leveraged to manipulate and extract data from multidimensional arrays efficiently.

Example: Extracting boundary elements from a matrix using array methods like `reduce()` and `forEach().

Javascript
function printBoundary(matrix) {
    const boundaryElements = matrix
        .reduce((acc, row, rowIndex) => {
            if (rowIndex === 0
                ||
                rowIndex === matrix.length - 1) {
                return acc
                    .concat(row);
            } else {
                return acc
                    .concat([row[0], row[row.length - 1]]);
            }
        }, []);
    boundaryElements
        .forEach(element => console.log(element));
}

// Example usage
const matrix = [
    [1, 2],
    [3, 4]
]

console.log("Boundary elements using array methods:");
printBoundary(matrix);

Output
Boundary elements using array methods:
1
2
3
4


Contact Us