Get the largest number from an array of numbers in JavaScript?

Answered
looper003 asked this question 21 days ago
looper003 21 days ago · Edited

I often am given an array of numbers:

[83, 321, 231,  21, 93, 142, 124, 221, 851]

And need to get the largest number.

How can I parse that array and return the largest number it contains?

Using JavaScript.

5 suggested answers
itsbambi 11 days ago

This will do the trick using the Array.reduce() method with Math.max() to get the largest number:

array.reduce((a, b) => Math.max(a, b))
0 replies
softwareguy411 11 days ago
Math.max.apply(Math, array)
0 replies
coderguy 11 days ago
array.sort((a, b) => b - a)[0]

This sorts the array in descending order:

array.sort((a, b) => b - a)

This will put the largest number at the beginning of the array.

You can retrieve that item at an index of 0:

array[0]
0 replies
yaboy01 11 days ago
Math.max(...array)
0 replies
coderguy 11 days ago

You can use a simple for loop as well:

var array = [83, 321, 231,  21, 93, 142, 124, 221, 851]

var maxValue = array[0]

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

// maxValue = 851
0 replies
Answered