JavaScript Program to Find maximum element of each row in a matrix


We will write a program that utilizes the future continuous tense in order to find the maximum element of each row in a given matrix. This will involve looping through each row of the matrix and comparing the elements to find the maximum value.

In order to implement this solution, we will use built-in functions such as Math.max() and loops to traverse the matrix and obtain the desired result. By the end of our program, we will have a solution that will be able to handle matrices of any size and provide the maximum value of each row in an efficient and effective manner.

Approach

Here is a brief explanation of the approach to find the maximum element of each row in a matrix using JavaScript −

  • Define a matrix with multiple rows and columns.

  • Loop through each row of the matrix.

  • Within each row, loop through each column and keep track of the maximum element found so far.

  • After looping through all columns, the current maximum element will be the maximum element of the current row.

  • Store the maximum element of each row in an array.

  • After looping through all rows, the array will contain the maximum element of each row.

  • Return the array as the result.

Example

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

function findMaxOfRows(matrix) {
   let result = [];
   for (let i = 0; i < matrix.length; i++) {
      let max = -Infinity;
      for (let j = 0; j < matrix[i].length; j++) {
         if (matrix[i][j] > max) {
            max = matrix[i][j];
         }
      }
      result.push(max);
   }
   return result;
}
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(findMaxOfRows(matrix)); 

Explanation

  • The function findMaxOfRows takes a 2D matrix as an argument.

  • The variable result is used to store the maximum element of each row.

  • The outer for loop iterates through each row of the matrix.

  • The inner for loop iterates through each element of the current row.

  • The if statement checks if the current element is greater than the current maximum. If it is, the maximum is updated with the current element.

  • After the inner for loop, the maximum of the current row is added to the result array.

  • The outer for loop continues until all the rows have been processed.

  • Finally, the result array is returned, which contains the maximum element of each row.

  • The sample matrix is passed as an argument to the findMaxOfRows function, and the result is logged to the console.

Updated on: 15-Mar-2023

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements