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});
We can find the smallest element or number in an array in java by sorting the array and returning the 1st element.
We will keep checking all the elements in the array using a loop. If we find any element greater than the previous “max” value, we set that value as the max value. Similarly, we keep on checking for any element lesser than the “min” value. If we get any such element, we replace the value of “min” with a smaller value.
The Math. min() function returns the smallest of zero or more numbers. The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.
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);
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]);
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With