jsRant asked this 2 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?


raj 2 years ago
1 like

Sort the array in ascending order and get first element

Best Answer by ben100
2 likes

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);