Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements