Skip to content

meanBy

Calculates the arithmetic mean of numbers derived from each item of an array via an iteratee. Returns NaN for an empty array, null, or undefined — matching sumBy, which treats null/undefined as empty rather than throwing.

Pairs with sumBy for aggregate operations.

Available since v3.0.3

import { meanBy } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { meanBy } from 'helpers4/array';
meanBy<T>(array: readonly T[] | null | undefined, accessor: ByAccessor<T>): number
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe array of items to average
accessorByAccessor<T>Function deriving a number from each item, or a property path

number — The arithmetic mean of the derived values, or NaN if the array is empty, null, or undefined

Averages a derived numeric value instead of the items themselves.

meanBy([{ price: 10 }, { price: 20 }], item => item.price)
// => 15

A string (or key array) path is shorthand for a getter function.

meanBy([{ price: 10 }, { price: 20 }], 'price')
// => 15

View source on GitHub