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 −
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