Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 ?
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
How It Works
The solution uses a helper function findSmallest that finds the minimum value in each row using reduce() with Math.min(). The main function iterates through each row, finds its minimum value, and adds it to the running sum.
For the given array:
- Row 1: [2, 5, 1, 6] ? minimum is 1
- Row 2: [6, 8, 5, 8] ? minimum is 5
- Row 3: [3, 6, 7, 5] ? minimum is 3
- Row 4: [9, 11, 13, 12] ? minimum is 9
- Sum: 1 + 5 + 3 + 9 = 18
Alternative Approach Using Map and Reduce
Here's a more concise solution using functional programming methods:
const arr = [
[2, 5, 1, 6],
[6, 8, 5, 8],
[3, 6, 7, 5],
[9, 11, 13, 12]
];
const sumSmallest = (arr) => {
return arr
.map(row => Math.min(...row))
.reduce((sum, min) => sum + min, 0);
};
console.log(sumSmallest(arr));
18
Using Math.min with Spread Operator
The spread operator (...) allows us to pass array elements as individual arguments to Math.min():
const findRowMinimums = (arr) => {
return arr.map(row => {
const minimum = Math.min(...row);
console.log(`Row [${row}] ? minimum: ${minimum}`);
return minimum;
});
};
const arr = [[7, 2, 8], [4, 1, 9], [6, 3, 5]];
const minimums = findRowMinimums(arr);
const totalSum = minimums.reduce((sum, min) => sum + min, 0);
console.log(`Total sum: ${totalSum}`);
Row [7,2,8] ? minimum: 2 Row [4,1,9] ? minimum: 1 Row [6,3,5] ? minimum: 3 Total sum: 6
Conclusion
Finding the sum of minimum values in a 2D array can be achieved using Math.min() with either reduce() or the spread operator. The functional approach with map() and reduce() provides a clean, readable solution.
