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


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

Updated on: 20-Apr-2021

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements