Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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});
like image 442
STEEL Avatar asked Oct 17 '13 16:10

STEEL


People also ask

How do you find the smallest element in an array?

We can find the smallest element or number in an array in java by sorting the array and returning the 1st element.

How do you find min and max values without math functions?

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.

Does math min work on arrays?

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.


3 Answers

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);
like image 82
MrCode Avatar answered Oct 16 '22 17:10

MrCode


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]);
like image 29
STEEL Avatar answered Oct 16 '22 17:10

STEEL


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];
like image 32
tenub Avatar answered Oct 16 '22 19:10

tenub