Highest and lowest in an array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that takes in an array of numbers and returns the difference between its highest and lowest number.

At first, create an array −

const arr = [23,54,65,76,87,87,431,-6,22,4,-454];

Now, find maximum and minimum values with Math.max() and Math.min() methods, respectively −

const arrayDifference = (arr) => {
   let min, max;
   arr.forEach((num, index) => {
      if(index === 0){
         min = num;
         max = num;
      }else{
         min = Math.min(num, min);
         max = Math.max(num, max);
   };
});

The complete code is as follows −

Example

const arr = [23,54,65,76,87,87,431,-6,22,4,-454];
const arrayDifference = (arr) => {
   let min, max;
   arr.forEach((num, index) => {
      if(index === 0){
         min = num;
         max = num;
      }else{
         min = Math.min(num, min);
         max = Math.max(num, max);
      };
   });
   return max - min;
};
console.log(arrayDifference(arr));

Output

The output in the console will be −

885
raja
Published on 19-Aug-2020 07:11:18
Advertisements