Getting the largest number from an array
JavaScriptAll snippets in this category →
Posted on Math.max()
returns the largest of zero or more numbers passed to it. We can use the spread operator when passing an array to get the largest number from that array.
// get the largest number from a list of numbers
Math.max(69, 420, 108, 47) // ⇒ 420
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.max(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.max(...numbers) // ⇒ 420
// get the largest number from a list of numbers
Math.max(69, 420, 108, 47) // ⇒ 420
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.max(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.max(...numbers) // ⇒ 420
// get the largest number from a list of numbers
Math.max(69, 420, 108, 47) // ⇒ 420
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.max(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.max(...numbers) // ⇒ 420
// get the largest number from a list of numbers
Math.max(69, 420, 108, 47) // ⇒ 420
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.max(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.max(...numbers) // ⇒ 420
The same works for Math.min()
.
// get the smallest number from a list of numbers
Math.min(69, 420, 108, 47) // ⇒ 47
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.min(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.min(...numbers) // ⇒ 47
// get the smallest number from a list of numbers
Math.min(69, 420, 108, 47) // ⇒ 47
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.min(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.min(...numbers) // ⇒ 47
// get the smallest number from a list of numbers
Math.min(69, 420, 108, 47) // ⇒ 47
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.min(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.min(...numbers) // ⇒ 47
// get the smallest number from a list of numbers
Math.min(69, 420, 108, 47) // ⇒ 47
// passing an array instead of individual numbers returns `NaN`
const numbers = [69, 420, 108, 47]
Math.min(numbers) // ⇒ NaN
// we get the expected result by spreading the array
const numbers = [69, 420, 108, 47]
Math.min(...numbers) // ⇒ 47