Function that returns the minimum and maximum value of an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array and return another array, the first element of this array should be the smallest element of input array and second should be the greatest element of the input array.

Example

Following is the code −

 Live Demo

const arr = [56, 34, 23, 687, 2, 56, 567];
const findMinMax = (arr = []) => {
   const creds = arr.reduce((acc, val) => {
   let [smallest, greatest] = acc;
      if(val > greatest){
         greatest = val;
      };
      if(val < smallest){
         smallest = val;
      };
      return [smallest, greatest];
   }, [Infinity, -Infinity]);
   return creds;
};
console.log(findMinMax(arr));

Output

[2, 687]
raja
Published on 17-Apr-2021 13:38:15
Advertisements