Returning an array with the minimum and maximum elements JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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[0]){
         acc[0] = 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 ]
raja
Published on 21-Aug-2020 13:19:34
Advertisements