Get the smallest number from an array of numbers using JavaScript?

Answered
itsbambi asked this question 21 days ago
itsbambi 21 days ago

When given an array of numbers like below:

[54, 322, 12, 24, . . .]

How do I get the smallest number in the array?

I'm using JavaScript to do this.

5 suggested answers
looper003 11 days ago

A solution in one line of code:

array.sort()[0]

It first sorts the array from smallest to largest:

array.sort()

This puts the smallest item in the first index position, which is retrieved like this:

array[0]
0 replies
nick 11 days ago

Using Math.min with rest parameters:

Math.min(...array)
0 replies
coderguy 11 days ago

You can loop through each value in the array and return the smallest one:

var array = [54, 322, 12, 24, 143, 343.32, 34.1]

var minValue = array[0]

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

// minValue = 12
0 replies
suparman21 11 days ago
Math.min.apply(Math, array)
0 replies
softwareguy411 11 days ago

The Array.reduce() method makes this quite easy:

array.reduce((a, b) => Math.min(a, b))
0 replies
Answered