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

Calculates the total sum of values in an array based on a selector function.

TypeScript
Copied!
1/**
2 * Calculates the total sum of values in an array based on a selector function.
3 *
4 * @param arr - The input array.
5 * @param fn - A function that extracts a number from each item.
6 * @returns The sum of selected values.
7 */
8export function sumBy<T>(arr: T[], fn: (item: T) => number): number {
9  return arr.reduce((total, item) => total + fn(item), 0);
10}
  • Custom Selector Function

    Supports complex data structures by letting you define how numeric values are extracted.

  • Concise and Efficient

    Implements a single-pass reduce for minimal overhead and fast performance.

  • Type-Safe and Generic

    Preserves type safety across a variety of input types using TypeScript generics.

  • Safe Default Behavior

    Returns 0 for empty arrays, avoiding NaN or undefined values in aggregations.

Tests | Examples

TypeScript
Copied!
1test('sumBy - sums numeric properties', () => {
2  const data = [
3    { amount: 10 },
4    { amount: 5 },
5    { amount: 3 },
6  ];
7  expect(sumBy(data, x => x.amount)).toBe(18);
8});
9
10test('sumBy - works with empty array', () => {
11  expect(sumBy([], x => x as number)).toBe(0);
12});
13
14test('sumBy - works with negative values', () => {
15  const data = [{ val: -2 }, { val: 4 }, { val: -1 }];
16  expect(sumBy(data, x => x.val)).toBe(1);
17});
18
19test('sumBy - handles floats correctly', () => {
20  const items = [{ price: 1.5 }, { price: 2.5 }];
21  expect(sumBy(items, x => x.price)).toBe(4.0);
22});

Common Use Cases

  • Financial Totals

    Calculate total cost, revenue, or expenses from lists of transactions or items.

  • Statistical Aggregation

    Sum numerical metrics like distances, durations, or scores in data analysis tasks.

  • UI Summaries

    Display totals in dashboards, tables, or reports (e.g., “Total Items Sold”).

  • Resource Management in Games/Apps

    Track total values like inventory weight, resource usage, or accumulated bonuses.

  • Log or Event Analysis

    Sum values like bytes transferred, request durations, or error counts from structured logs.

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