Syntax, Parameter and Return Value
Syntax:
_.max(array)
Parameters:
array (Array): The array to iterate over.
Return Value:
(Number) - Returns the maximum value found in the array. If the array is empty or falsey, _.max() returns undefined.
Examples
Basic Usage to Find Maximum Value:
JavaScript
var _ = require('lodash');
console.log(_.max([4, 2, 8, 6]));

You can also try this code with Online Javascript Compiler
Run Code
Output:
8
Demonstrates finding the largest number in a simple array.
Handling Empty Array:
JavaScript
console.log(_.max([]));

You can also try this code with Online Javascript Compiler
Run Code
Output:
undefined
Shows that _.max() returns undefined when applied to an empty array.
Application in Data Analysis:
JavaScript
var scores = [76, 85, 90, 95, 88];
var highestScore = _.max(scores);
console.log('Highest Score:', highestScore);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Highest Score: 95'
An example of using _.max() to find the highest score in a collection of numerical data.
Comparing with Native JavaScript Methods:
JavaScript
var numbers = [10, 21, 3, 15];
var maxNumber = Math.max(...numbers);
console.log(maxNumber);

You can also try this code with Online Javascript Compiler
Run Code
Output:
21
Demonstrates achieving a similar result with native JavaScript's Math.max() for comparison.
Frequently Asked Questions
Does _.max() work with non-numeric values?
_.max() is designed for arrays of numbers. Non-numeric values in the array are ignored in the calculation, and may lead to undefined if no numeric values are present.
How does _.max() handle NaN or undefined values in the array?
NaN or undefined values in the array are ignored by _.max(), and they do not affect the calculation of the maximum value.
Can _.max() be used with arrays of objects?
To find the maximum value in an array of objects based on a specific property, you should use _.maxBy() instead, which allows specifying an iteratee for comparison.
Conclusion
Lodash's _.max() method offers a straightforward solution for finding the maximum value in an array of numbers. It enhances code readability and efficiency, especially in comparison to more verbose native JavaScript approaches in certain scenarios.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.