Highest and lowest in an array JavaScript



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
Updated on: 2020-08-19T07:11:58+05:30

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements