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
Return the maximum number in each array using map JavaScript
We have an array of arrays of Numbers like this one:
const arr = [ [12, 56, 34, 88], [65, 66, 32, 98], [43, 87, 65, 43], [32, 98, 76, 83], [65, 89, 32, 54], ];
We are required to write a function that maps over this array of arrays and returns an array that contains the maximum (greatest) element from each subarray.
Using Math.max() with Spread Operator
The most straightforward approach is to use Math.max() with the spread operator to find the maximum value in each subarray:
const arr = [
[12, 56, 34, 88],
[65, 66, 32, 98],
[43, 87, 65, 43],
[32, 98, 76, 83],
[65, 89, 32, 54],
];
const findMax = arr => {
return arr.map(sub => {
const max = Math.max(...sub);
return max;
});
};
console.log(findMax(arr));
[ 88, 98, 87, 98, 89 ]
Simplified Version
We can make the function more concise by directly returning the result of Math.max():
const arr = [ [12, 56, 34, 88], [65, 66, 32, 98], [43, 87, 65, 43], [32, 98, 76, 83], [65, 89, 32, 54], ]; const findMax = arr => arr.map(sub => Math.max(...sub)); console.log(findMax(arr));
[ 88, 98, 87, 98, 89 ]
Using reduce() Alternative
For comparison, here's how you could find the maximum using reduce() instead of Math.max():
const arr = [
[12, 56, 34, 88],
[65, 66, 32, 98],
[43, 87, 65, 43],
];
const findMaxWithReduce = arr => {
return arr.map(sub =>
sub.reduce((max, current) => current > max ? current : max)
);
};
console.log(findMaxWithReduce(arr));
[ 88, 98, 87 ]
How It Works
The map() method creates a new array by calling the provided function for each element. In our case:
-
Math.max(...sub)spreads each subarray and finds its maximum value - The spread operator
...expands the array elements as individual arguments - Each maximum value becomes an element in the resulting array
Conclusion
Using map() with Math.max() and the spread operator provides an elegant solution to find maximum values in nested arrays. This approach is both readable and efficient for this type of transformation.
