For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/bigint/sumBy.md.

sumBy (for BigInts) es-toolkit

Returns the sum of the BigInts that a function derives from each element of an array.

const total = sumBy(items, getValue);
Info

This function is available exclusively from es-toolkit/bigint to avoid potential conflicts with similar functions for other numeric types.

Usage

sumBy(items, getValue)

Use sumBy when the BigInts you want to add up are inside objects. Pass a function that pulls the value out of each element, and it adds up everything that function returns.

import { sumBy } from 'es-toolkit/bigint';

// Sum a field of each object
const accounts = [{ balance: 10n }, { balance: 20n }, { balance: 30n }];
const total = sumBy(accounts, account => account.balance);
console.log(total); // 60n

// The index is passed as the second argument
const weights = sumBy(['a', 'b', 'c'], (_, index) => BigInt(index));
console.log(weights); // 3n

An empty array returns 0n, and values can be negative.

import { sumBy } from 'es-toolkit/bigint';

console.log(sumBy([], () => 1n)); // 0n

const entries = [{ amount: -500n }, { amount: 1200n }, { amount: -200n }];
console.log(sumBy(entries, entry => entry.amount)); // 500n

Parameters

itemsreadonly T[]required

The array of elements to sum.

getValue(element: T, index: number) => bigintrequired

A function that returns the BigInt to add for each element.

Returns

Returns the sum of every value returned by getValue. Returns 0n for empty arrays.

bigint
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.