How to find the maximum element of an array?
Short answer
The maximum element of an unsorted array is found in O(n). For small arrays, Math.max(...arr) is convenient; for reliability and large arrays, a plain loop is better.
function max(arr) {
if (arr.length === 0) return undefined; // or throw an error
let m = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > m) m = arr[i];
}
return m;
}
// Example
console.log(max([3, 10, -5])); // 10Detailed answer
Solution variants
-
Math.max with spread (simple and clear, fits small arrays):
javascriptconst arr = [3, 10, -5]; const max1 = Math.max(...arr); // 10 // Important: Math.max(...[]) === -Infinity; empty arrays need a separate check. // For very large arrays, spread can throw a "Too many arguments" error. -
reduce (concise, but account for an empty array):
javascriptconst arr = [3, 10, -5]; const max2 = arr.reduce((m, x) => (x > m ? x : m), -Infinity); // 10 // Returns -Infinity for an empty array, check separately if that is not acceptable. -
A plain loop (the most reliable and fastest for large arrays):
javascriptfunction maxLoop(arr) { if (arr.length === 0) return undefined; let m = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] > m) m = arr[i]; } return m; } console.log(maxLoop([3, 10, -5])); // 10
A reliable implementation with checks
The strict variant: numbers only, NaN forbidden. Throws on invalid data.
function maxNumberStrict(arr) {
if (!Array.isArray(arr)) throw new TypeError('Expected an array');
if (arr.length === 0) return undefined; // or throw
let m;
for (let i = 0; i < arr.length; i++) {
const v = arr[i];
if (typeof v !== 'number' || Number.isNaN(v)) {
throw new TypeError('Array must contain only valid numbers');
}
if (m === undefined || v > m) m = v;
}
return m;
}
console.log(maxNumberStrict([4, 1, 9, 2])); // 9The tolerant variant: tries to coerce values to a number, skipping non-numeric/infinite ones. Convenient for "dirty" data.
function maxNumberSafe(arr) {
let m = -Infinity;
for (const v of arr) {
const num = Number(v);
if (!Number.isFinite(num)) continue; // skip NaN/Infinity/non-numeric
if (num > m) m = num;
}
return m === -Infinity ? undefined : m;
}
console.log(maxNumberSafe(["7", 3, null, 12, NaN])); // 12
console.log(maxNumberSafe([])); // undefinedAn array of objects (max by a field)
function maxBy(arr, selector) {
if (arr.length === 0) return undefined;
let best = arr[0];
let bestKey = selector(best);
for (let i = 1; i < arr.length; i++) {
const key = selector(arr[i]);
if (key > bestKey) {
best = arr[i];
bestKey = key;
}
}
return best;
}
const users = [
{ name: 'A', age: 19 },
{ name: 'B', age: 27 },
{ name: 'C', age: 23 },
];
const oldest = maxBy(users, u => u.age);
console.log(oldest); // { name: 'B', age: 27 }Complexity, sorting, and large arrays
-
Complexity: O(n) time and O(1) memory (for a loop/reduce).
-
Do not sort an array just to find the maximum: sorting is O(n log n), which is worse than a single pass.
-
Avoid Math.max(...arr) for very large arrays: it can throw due to an argument count limit. Use a loop.
-
Iterate a TypedArray (Float64Array, etc.) with a loop; that is efficient and safe.
-
BigInt: Math.max does not work with BigInt. Use a BigInt comparison loop:
javascriptfunction maxBigInt(arr) { if (arr.length === 0) return undefined; let m = arr[0]; // assume BigInt for (let i = 1; i < arr.length; i++) if (arr[i] > m) m = arr[i]; return m; } console.log(maxBigInt([1n, 5n, 3n])); // 5n
Edge cases and correctness
- Empty array: return undefined or throw; Math.max(...[]) gives -Infinity, which is usually not what you want.
- NaN/Infinity: decide the policy ahead of time: ignore, throw, or return NaN. Be consistent.
- Mixed types: coercing to a number can produce NaN; in the "strict" version it is better to validate types.
- An already-sorted array: the maximum is the last element, but if the array is not guaranteed to be sorted, an O(n) pass is still needed.
Quick recommendations
- Small arrays: Math.max(...arr) with a check for an empty array.
- Large arrays or performance: the classic loop.
- "Dirty" data: the variant that skips non-numeric values (maxNumberSafe).
- An array of objects: use maxBy with a field selector.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.