
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
Find Difference Between Largest and Smallest Number in Array in JavaScript
We have an array of Numbers that are arranged in pure random order. Our job is to write a function that takes in one such array of Numbers and returns the difference of greatest and smallest numbers present in it, but without sorting the array.
Therefore, let's write the code for this function −
We will use the Array.prototype.reduce() function to pick the smallest and greatest numbers from the array and later will return their difference. The code for this function will be −
Example
const arr = [23, 65, 67, 23, 2, 6, 87, 23, 45, 65, 3, 234, 3]; const findDifference = arr => { if(!arr.length){ return 0; } const creds = arr.reduce((acc, val) => { let { max, min } = acc; if(val > max){ max = val; }; if(val < min){ min = val; }; return { max, min }; }, { max: -Infinity, min: Infinity }); return creds.max - creds.min; }; console.log(findDifference(arr));
Output
The output in the console will be −
232
Advertisements