Syntax, Parameter and Return Value
Syntax:
_.mean(array)
Parameters:
array (Array): The array of numbers to calculate the mean.
Return Value:
(Number) - Returns the mean of the array.
Examples
Basic Mean Calculation:
JavaScript
var _ = require('lodash');
console.log(_.mean([4, 2, 8, 6]));

You can also try this code with Online Javascript Compiler
Run Code
Output:
5
Demonstrates the basic usage of _.mean() to calculate the average of an array of numbers.
Calculating Average Score:
JavaScript
var scores = [70, 85, 90, 100, 80];
var averageScore = _.mean(scores);
console.log('Average Score:', averageScore);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Average Score: 85'
Shows calculating the average score from an array of test scores.
Using with Complex Data Structures:
JavaScript
var employees = [
{ name: 'John', salary: 50000 },
{ name: 'Jane', salary: 60000 },
{ name: 'Joe', salary: 55000 }
];
var averageSalary = _.mean(_.map(employees, 'salary'));
console.log('Average Salary:', averageSalary);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Average Salary: 55000'
An example of calculating the mean salary from an array of objects using Lodash’s _.map().
Handling Empty Arrays:
JavaScript
console.log(_.mean([]));

You can also try this code with Online Javascript Compiler
Run Code
Output:
NaN
Demonstrates that _.mean() returns NaN when applied to an empty array.
Frequently Asked Questions
How does _.mean() handle non-numeric values in the array?
_.mean() ignores non-numeric values when calculating the mean. However, the presence of such values may affect the calculation, leading to unexpected results.
Can _.mean() be used with large data sets?
Yes, _.mean() can be used with large data sets. However, for extremely large arrays, consider performance implications as the entire array needs to be iterated over.
Is _.mean() the best choice for all average calculations?
_.mean() is suitable for basic average calculations. For weighted averages or other complex statistical computations, specialized libraries or custom functions may be more appropriate.
Conclusion
Lodash's _.mean() method offers a straightforward and efficient way to calculate the average of numerical values in an array. It simplifies and enhances the readability of code involving statistical calculations and data analysis.
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.