jsRant asked this 8 years ago

Javascript: how to get smallest value from array?

I know we can use Math.min to do this

.apply() on Math function makes it accept unlimited arguments

Array.min = function( array ){
    return Math.min.apply( Math, array );
};

How to do this without using Math.min?


Best Answer by ben100 8 years ago

You dont need to sort the whole array, a more efficient way is to do this in a single for loop.

var smallest = arr[0];

for (var i=0; i<arr.length; i++)
  {
    if (arr[i] < smallest)
      smallest = arr[i];
  }

console.log(smallest);

 

raj 8 years ago
1 like

Sort the array in ascending order and get first element