Skip to content

max

Returns the maximum value in an array using a loop instead of spread, avoiding the call stack overflow that occurs with Math.max(...array) for very large arrays (> ~65 000 elements). null and undefined are treated as empty arrays and return undefined.

Available since v2.0.2

import { max } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { max } from 'helpers4/array';
max(array: readonly number[] | null | undefined): number | undefined
ParameterTypeDescription
arrayreadonly number[] | null | undefinedArray of numbers

number | undefined — Maximum value, undefined for empty arrays, null, undefined, or NaN if any element is NaN

Unlike Math.max(…array), max() uses a loop and handles arrays of any size without stack overflow.

max([3, 1, 4, 1, 5, 9])
// => 9

// Safe for 1 000 000+ elements (Math.max(...arr) would throw):
max(Array.from({ length: 1_000_000 }, (_, i) => i))
// => 999999

View source on GitHub