Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements