Skip to content

sumBy() function

Returns the sum of the values produced by applying f to each element of the given Iterable/AsyncIterable. Returns 0 for an empty iterable.

Signature:

typescript
declare function sumBy<A>(f: (a: A) => number, iterable: Iterable<A>): number;

Example

ts
sumBy((a) => a.price, [
  { name: "apple", price: 100 },
  { name: "banana", price: 200 },
]); // 300

sumBy((a) => a.price, []); // 0

// with pipe
pipe(
  [{ price: 100 }, { price: 200 }],
  sumBy((a) => a.price),
); // 300

Open Source Code

Released under the Apache-2.0 License.