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
Build maximum array based on a 2-D array - JavaScript
Let's say, we have an array of arrays of Numbers like below −
const arr = [ [1, 16, 34, 48], [6, 66, 2, 98], [43, 8, 65, 43], [32, 98, 76, 83], [65, 89, 32, 4], ];
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.
So, for the above array, the output should be −
[48, 98, 65, 98, 89]
Using Math.max() with Spread Operator
The most efficient approach uses Math.max() with the spread operator to find the maximum value in each subarray:
const arr = [
[1, 16, 34, 48],
[6, 66, 2, 98],
[43, 8, 65, 43],
[32, 98, 76, 83],
[65, 89, 32, 4],
];
const constructBig = arr => {
return arr.map(sub => {
const max = Math.max(...sub);
return max;
});
};
console.log(constructBig(arr));
[48, 98, 65, 98, 89]
Simplified Version
We can make the function more concise by directly returning the Math.max result:
const arr = [
[1, 16, 34, 48],
[6, 66, 2, 98],
[43, 8, 65, 43],
[32, 98, 76, 83],
[65, 89, 32, 4],
];
const getMaxFromEachArray = arr => {
return arr.map(sub => Math.max(...sub));
};
console.log(getMaxFromEachArray(arr));
[48, 98, 65, 98, 89]
Alternative: Using reduce() Method
Another approach uses the reduce() method to find the maximum in each subarray:
const arr = [
[1, 16, 34, 48],
[6, 66, 2, 98],
[43, 8, 65, 43],
[32, 98, 76, 83],
[65, 89, 32, 4],
];
const getMaxWithReduce = arr => {
return arr.map(sub => {
return sub.reduce((max, current) => {
return current > max ? current : max;
});
});
};
console.log(getMaxWithReduce(arr));
[48, 98, 65, 98, 89]
Comparison
| Method | Performance | Readability |
|---|---|---|
Math.max(...sub) |
Fast | Very clean |
reduce() |
Slightly slower | More verbose |
Conclusion
Using Math.max() with the spread operator is the most efficient and readable way to extract maximum values from each subarray. The map() method handles the iteration over the 2D array structure.
