Suggest an editImprove this articleRefine the answer for “How to find the maximum element of an array?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**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. **Key point:** do not sort an array just to find the maximum: sorting costs O(n log n), which is worse than a single pass.Shown above the full answer for quick recall.Answer (EN)Image## 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. ```javascript 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])); // 10 ``` ## Detailed answer ### Solution variants - Math.max with spread (simple and clear, fits small arrays): ```javascript const 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): ```javascript const 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): ```javascript function 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. ```javascript 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])); // 9 ``` The tolerant variant: tries to coerce values to a number, skipping non-numeric/infinite ones. Convenient for "dirty" data. ```javascript 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([])); // undefined ``` ### An array of objects (max by a field) ```javascript 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: ```javascript function 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 1. Empty array: return undefined or throw; Math.max(...[]) gives -Infinity, which is usually not what you want. 2. NaN/Infinity: decide the policy ahead of time: ignore, throw, or return NaN. Be consistent. 3. Mixed types: coercing to a number can produce NaN; in the "strict" version it is better to validate types. 4. 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.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.