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

Answered
itsbambi asked this question 7 months ago
itsbambi on Jan 4

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 on Jan 14

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 on Jan 14

Using Math.min with rest parameters:

Math.min(...array)
0 replies
coderguy on Jan 14

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 on Jan 14
Math.min.apply(Math, array)
0 replies
softwareguy411 on Jan 14

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

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