Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

sumBy

Sums up the values in an array based on a selector function.

TypeScript
Copied!
1/**
2 * Sums up the values in an array based on a selector function.
3 *
4 * @param arr - The array of items.
5 * @param fn - A function that returns a numeric value for each item.
6 * @returns The total sum.
7 */
8export function sumBy<T>(arr: T[], fn: (item: T) => number): number {
9  return arr.reduce((total, item) => total + fn(item), 0);
10}
  • Flexible aggregation

    Accepts a selector function to extract numeric values, allowing it to sum based on any property or computation.

  • Generic and type-safe

    Supports any type of item in the array, as long as the selector returns a number — ideal for structured data.

  • Non-mutating

    Does not modify the original array, which helps preserve functional purity.

  • Handles empty arrays gracefully

    Returns 0 for an empty array, avoiding NaN or unexpected behavior.

  • Concise and performant

    Leverages a single-pass .reduce() loop for optimal performance and readability.

Tests | Examples

TypeScript
Copied!
1test('sumBy - sum object property values', () => {
2  const data = [{ price: 10 }, { price: 20 }, { price: 5 }];
3  expect(sumBy(data, item => item.price)).toBe(35);
4});
5
6test('sumBy - sum derived values', () => {
7  const data = ['foo', 'bar', 'hello'];
8  expect(sumBy(data, s => s.length)).toBe(11);
9});
10
11test('sumBy - empty array returns 0', () => {
12  expect(sumBy([], () => 42)).toBe(0);
13});
14
15test('sumBy - handles negative values', () => {
16  const data = [{ n: 3 }, { n: -5 }, { n: 7 }];
17  expect(sumBy(data, item => item.n)).toBe(5);
18});

Common Use Cases

  • Financial calculations

    Summing prices, subtotals, invoices, or expenses from a list of objects.

  • Analytics and metrics

    Aggregating numeric stats like views, likes, downloads, time spent, or error counts.

  • Inventory or stock systems

    Summing quantities, weights, or volumes across items.

  • Game development

    Totals from player scores, damage outputs, or item values.

  • Custom data transformation

    Can be used in a functional chain with map, filter, or groupBy to derive high-level summaries.

Codebase: Utilities -> Arrays -> sumBy | Yevhen Klymentiev