'Find smallest value in Array without Math.min
How can I find the lowest number in an array without using Math.min.apply?
var arr = [5,1,9,5,7];
const smallest = Math.min(...[5,1,9,5,7]);
console.log({smallest});
//old way
const smallestES5 = Math.min.apply(null, [5,1,9,5,7]);
console.log({smallestES5});
Solution 1:[1]
Now when look at my own question.. it looks so silly of me.
Below would be perfect solution to find the smallest number in an array:
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts
var arr = [5, 1, 9, 5, 7];
var smallest = arr.sort((a, b) => a - b);
alert(smallest[0]);
Solution 2:[2]
If you must use a for loop:
var arr = [5,1,9,5,7];
var smallest = arr[0];
for(var i=1; i<arr.length; i++){
if(arr[i] < smallest){
smallest = arr[i];
}
}
console.log(smallest);
Solution 3:[3]
just sort the array and take the first value, easy.
if you must use a for loop:
var arr = [5,1,9,5,7];
for (var i=0; i<1; i++) {
arr.sort();
}
return arr[0];
Solution 4:[4]
Here's a simple solution using a for loop.
var arr = [5,1,9,5,7];
var smallest = arr[0];
for (var i=0; i<arr.length; i++){
if (arr[i]<smallest){
smallest = arr[i];
}
}
return smallest;
Returns 1.
Solution 5:[5]
Alternate solution without using for loop (ES6). JavaScript reduce method is a good choice.
var arr = [5,1,9,5,7];
var smallest = arr.reduce((prev,next) => prev>next ? next : prev);
var largest = arr.reduce((prev,next) => prev<next ? next : prev);
Solution 6:[6]
you can try this
const min = (arr) => {
return arr.sort((a, b) => a - b)[0];
};
this min() function should make the job done
Solution 7:[7]
var arr = [5, 1, 9, 5, 7,-1,0,5,11,100,-0.5];
var smallest = arr.sort();
console.log(smallest[0]);
Solution 8:[8]
Make a function so you can reuse it as per your needs. Here I just showed an example of the smallest number finder.
function smallestNumber(number){
let min = number[0];
for(let i = 0; i < number.length; i++){
let element = number[i];
if( element < min ){
min = element
}
}
return min;
}
let totalNum = [25,50,75,56,11,50,7,9,12];
let result = smallestNumber(totalNum);
console.log('The small number is : ',result);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | MrCode |
| Solution 3 | |
| Solution 4 | |
| Solution 5 | saran |
| Solution 6 | Nawaz Haider |
| Solution 7 | Ravi Ashara |
| Solution 8 | Md Yunus Ali |
