Skip to main content

sum

Returns the sum of array elements.

By default, it returns the sum of a number array. For arrays of other types, the sum can be determined by the result of the second argument iteratee function.


Code

🔗 View source code


Benchmark

  • hz: operations per second
  • mean: average response time (ms)
NamehzmeanPerformance
modern-kit/sum21,825,119.560.0000fastest
lodash/sum7,861,063.970.0001-
  • modern-kit/sum
    • 2.78x faster than lodash/sum
NamehzmeanPerformance
modern-kit/sum with iteratee15,978,576.340.0001fastest
lodash/sumBy4,471,676.860.0002-
  • modern-kit/sum with iteratee
    • 3.57x faster than lodash/sumBy

Interface

typescript
// Function overloading
function sum(arr: number[] | readonly number[]): number;

function sum<T>(
arr: T[] | readonly T[],
iteratee: (item: T) => number
): number;

Usage

Default

typescript
import { sum } from '@modern-kit/utils';

const arr = [1, 2, 3, 4, 5];
const result = sum(arr); // 15

Iteratee

typescript
import { sum } from '@modern-kit/utils';

const arr = [
{ value: 1 },
{ value: 2 },
{ value: 3 },
{ value: 4 },
{ value: 5 },
];
const result = sum(arr, (item) => item.value); // 15