How Lodash meanBy Works on Array of Objects

Lodash provides the _.meanBy utility method to calculate the arithmetic mean of values produced by iterating over a collection. When applied to an array of objects, it extracts a specific numerical metric from each object using an iteratee and computes the average. This article breaks down the internal iteration mechanism of _.meanBy, illustrates how the iteratee resolves values, and demonstrates its practical application in JavaScript.

The Iteration Process

Under the hood, _.meanBy combines an iteration mechanism with an iteratee resolver. When calling _.meanBy(array, [iteratee=_.identity]) on an array of objects, Lodash executes the following sequence:

  1. Iteratee Resolution: Lodash evaluates the second argument. If provided as a string (such as 'score'), Lodash wraps it using _.property to retrieve that property path from each object. If provided as a callback function, that function is invoked directly on each item.
  2. Sequential Traversal: Lodash iterates over the array elements using an internal loop (relying on baseSum).
  3. Value Mapping and Accumulation: During each step of the loop, the current object is passed to the iteratee. The returned numerical value is added to an accumulator tracking the running total.
  4. Mean Calculation: Once traversal is complete, the total accumulated sum is divided by the length of the array (sum / array.length).

If the input array is empty, the function returns NaN, matching the standard mathematical outcome of dividing zero by zero.

Practical Code Examples

Using a property path shorthand is the most common way to iterate through an array of objects with _.meanBy:

const _ = require('lodash');

const inventory = [
  { item: 'Widget A', price: 25 },
  { item: 'Widget B', price: 40 },
  { item: 'Widget C', price: 55 }
];

// Using property name shorthand
const averagePrice = _.meanBy(inventory, 'price');
console.log(averagePrice); // Output: 40

You can also pass a custom function if the property requires conversion, mathematical adjustment, or nested extraction:

const scores = [
  { student: 'Alex', results: { final: 80 } },
  { student: 'Jordan', results: { final: 90 } },
  { student: 'Taylor', results: { final: 100 } }
];

// Using a custom iteratee callback
const averageScore = _.meanBy(scores, (record) => record.results.final);
console.log(averageScore); // Output: 90

Handling Non-Numeric Values and Edge Cases

Because _.meanBy relies on standard JavaScript addition during its accumulation step, the iteratee must resolve to a valid number. If an object is missing the target property, or if the iteratee returns undefined, null, or a non-numeric value, the addition operation produces NaN, causing the final result to be NaN. To prevent this when handling unpredictable datasets, ensure the iteratee provides a fallback default value (such as record.value || 0).