Skip to content

sumBy

Calculates the sum of numbers derived from each item of an array via an iteratee. null and undefined are treated as empty arrays and return 0.

Available since v3.0.3

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

number — The sum of all derived values, or 0 for an empty array, null, or undefined

Sums a derived numeric value instead of the items themselves.

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

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

sumBy([{ price: 10 }, { price: 20 }], 'price')
// => 30

View source on GitHub