2 Easy Ways To find the difference between largest and smallest numbers in array Javascript

Today we are going to learn different methods to find the difference between largest and smallest numbers in array javascript.

We already saw how to find smallest number in array and find largest number in array javascript. With the help of these two methods we are going to find difference between largest and smalles numbers in array.

Smallest Number and Largest Number

Difference between largest and smallest numbers in array using Math.min() and Math.max()

First we are going to find largest number,

let arr = [10, 20, 30, 40, 50];

Using spread operator we are going to spread out the array as series of elements then pass it to Math.max() function.

let largestNumber = Math.max(...arr);

console.log(largestNumber);

Now we are going to find the smallest number from the array,

Using spread operator we are going to spread out the array as series of elements then pass it to Math.min() function.

let smallestNumber = Math.min(...arr);

console.log(smallestNumber);

It’s time to find the difference between largest and smallest number,

let differnce = largestNumber - smallestNumber;
console.log(difference);

Difference between largest and smallest numbers in array using lodash

We are going to find the difference using lodash javascript library.

First we are going to find largest number,

let arr = [10, 20, 30, 40, 50];
let largestNumber = _.max(arr);

Read more about how to find largest number using lodash here

Now we are going to find the smallest number in array,

let differnce = largestNumber - smallestNumber;
console.log(difference);

Conclusion:

I hope you learned how to find the difference between largest and smallest number in array using javascript.

You can read more about javascript at Javascript.info