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
Selected Reading
Returning an array with the minimum and maximum elements JavaScript
Provided an array of numbers, let’s say −
const arr = [12, 54, 6, 23, 87, 4, 545, 7, 65, 18, 87, 8, 76];
We are required to write a function that picks the minimum and maximum element from the array and returns an array of those two numbers with minimum at index 0 and maximum at 1.
We will use the Array.prototype.reduce() method to build a minimum maximum array like this −
Example
const arr = [12, 54, 6, 23, 87, 4, 545, 7, 65, 18, 87, 8, 76];
const minMax = (arr) => {
return arr.reduce((acc, val) => {
if(val acc[1]){
acc[1] = val;
}
return acc;
}, [Infinity, -Infinity]);
};
console.log(minMax(arr));
Output
The output in the console will be −
[ 4, 545 ]
Advertisements
