es-toolkit/docs/reference/math/sumBy.md
Youngjun Choi 3441d7d8d0
feat(sumBy): add sumBy (#198)
* feat: add sumBy function

* feat: add sumBy test

* feat: add sumBy bench

* feat: add sumBy documentation
2024-07-15 08:25:49 +09:00

659 B

sumBy

Calculates the sum of an array of numbers when applying the getValue function to each element.

If the array is empty, this function returns 0.

Signature

export function sumBy<T>(items: T[], getValue: (element: T) => number): number;

Parameters

  • items (T[]): An array to calculate the sum.
  • getValue ((item: T) => number): A function that selects a numeric value from each element.

Returns

(number): The sum of all the numbers as determined by the getValue function.

Examples

sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: 6
sumBy([], x => x.a); // Returns: 0