3 Easy Ways To Find smallest number in array using JavaScript
January 17, 2021We are going to learn different methods to find smallest number in array using Javascript.
Find smallest number using Sort method
We are going to write a function to find smallest number in array using sort method.
let arr = [10, 20, 30, 40, 50];
The smallest number of the above array is 10.
Let’s write the program to find smallest number.
function findSmallestNumber(arr) {
let smallest = arr.sort((a, b) => a - b);
return smallest[0];
}
Explanation:
In the above program we are using array sort method to find smallest number.
The array sort provide the result in ascending order [10,20,30,40,50]. Then we should return first element arr[0] which is the smallest number.
let smallestNumber = findSmallestNumber(arr);
console.log(smallestNumber);
You can check the above function in your browser console or checkout my CodePen.
Find smallest number in array using JavaScript Math.min Function
In this method, we are going to use Math.min(). Math.min() function get an arguments as series of number input and return the smallest number.
Example: Math.min(10,20,30,40,50) this will give result 10.
If we pass Array to Math.min() it will return Nan.
Example: Math.min([10,20,30,40,50]) this will give result as Nan.
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.min() function. Read more about Math.min() here. Read about spread operator here.
let smallestNumber = Math.min(...arr);
console.log(smallestNumber);
You can check the above function in your browser console or checkout my CodePen.
Find smallest number in array using lodash
Lodash is a javascript library that provides utility functions for common programming tasks. we cannot test lodash program in usual browser console. Go to the Lodash’s Official website and open console then execute lodash program.
let arr = [10, 20, 30, 40, 50];
let smallestNumber = _.min(arr);
console.log(smallestNumber);
It will provide result as 10.
Try to learn lodash it makes your javascript life easier.
You can check the above function in your lodash website browser console or checkout my CodePen.
Conclusion: We hope you learned few new things to find smallest number in array.
In this tutorial we have found 3 ways to find a smallest number in the javascript array. There are many ways to solve same problem for that we have to keep learn and practice javascript.
If you know any other ways to find the smallest number you can put it in comment.
If you want us to explain other javascript problems put in the comment we will try to explain at our best.
Recent Blog: How to find largest number in array using JavaScript?