Finding the sum of minimum value in each row of a 2-D array using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a 2-D array of numbers. Our function should pick the smallest number from each row of the 2-D array and then finally return the sum of those smallest numbers.

Example

Following is the code −

 Live Demo

const arr = [
   [2, 5, 1, 6],
   [6, 8, 5, 8],
   [3, 6, 7, 5],
   [9, 11, 13, 12]
];
const sumSmallest = (arr = []) => {
   const findSmallest = array => array.reduce((acc, val) => {
      return Math.min(acc, val);
   }, Infinity)
   let sum = 0;
   arr.forEach(sub => {
      sum += findSmallest(sub);
   });
   return sum;
};
console.log(sumSmallest(arr));

Output

18
raja
Published on 20-Apr-2021 09:49:01
Advertisements