Find the difference of largest and the smallest number in an array without sorting it in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 31-Aug-2020 10:15:18
Advertisements