Find Maximum Element of Each Row in a Matrix using JavaScript



In JavaScript, the 2D matrix manipulation involves working with arrays of arrays, often to perform operations on rows or columns. In this example, we focus on finding the maximum value in each row of a matrix. Two methods are demonstrated: using nested loops for step-by-step iteration, and using map() with Math.max() for a more concise, functional approach. Both methods return an array of the maximum values from each row, but the map() approach is more efficient and modern.

Different approaches

Following are the different approaches to finding maximum element of each row in a matrix ?

Using Nested Loops

The most straightforward way to find the maximum element in each matrix row is by using nested loops. This method involves iterating through each row and comparing each component to find the largest value.

How it Works

Here, we will iterate over each row in the matrix ?

for (let row of matrix){}

Initialize the maximum value (max) as the first element of the row ?

let max = row[0];

Using the .push method we will store the max for each row in a result array ?

result.push(max);

Example

Here is a complete example of a JavaScript program that finds the maximum element of each row in a matrix ?

function findMaxInRows(matrix) {
    const result = [];

    for (let row of matrix) {
        let max = row[0]; // Initialize max as the first element of the row
        for (let element of row) {
            if (element > max) {
                max = element; // Update max if a larger value is found
            }
        }
        result.push(max); // Store the max value for the row
    }

    return result;
}

// Example Matrix
const matrix = [
    [3, 8, 1],
    [5, 12, 7],
    [9, 4, 6],
];
console.log(findMaxInRows(matrix));

Output

[8, 12, 9]

Using map() with Math.max()

JavaScript's built-in map() function, along with Math.max(), offers a more elegant and concise way to find the maximum element in each row. The map() function allows us to apply a given function to each element of an array and return a new array with the results. When combined with Math.max(), it can help us find the maximum value for each row.

How it Works

Use the map() method to iterate over each row of the matrix?

matrix.map();

For each row, use the spread operator (...) to expand the row array and pass it to Math.max() to find the maximum element?

(row => Math.max(...row));

Example

Here is a complete example of a JavaScript program that finds the maximum element of each row in a matrix ?

function findMaxInRows(matrix) {
    return matrix.map(row => Math.max(...row));
}

// Example Matrix
const matrix = [
    [3, 8, 1],
    [5, 12, 7],
    [9, 4, 6],
];

console.log(findMaxInRows(matrix));

Output

[8, 12, 9]

Updated on: 2024-12-06T01:42:02+05:30

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements