Skip to content

sum

Calculate the sum of all numbers in an array.

Basic Usage

typescript
import { sum } from 'radash'

const numbers = [1, 2, 3, 4, 5]
const total = sum(numbers)
// 15

Syntax

typescript
function sum(array: readonly number[]): number

Parameters

  • array (readonly number[]): The array of numbers to sum

Return Value

Returns the sum of all numbers in the array. If the array is empty, returns 0.

Examples

Basic Summation

typescript
import { sum } from 'radash'

console.log(sum([1, 2, 3, 4, 5]))     // 15
console.log(sum([10, 20, 30]))        // 60
console.log(sum([-1, -2, -3]))        // -6
console.log(sum([0, 0, 0]))           // 0

Handle Empty Arrays

typescript
import { sum } from 'radash'

console.log(sum([]))                   // 0
console.log(sum([0]))                  // 0

Handle Decimals

typescript
import { sum } from 'radash'

console.log(sum([1.5, 2.5, 3.5]))     // 7.5
console.log(sum([0.1, 0.2, 0.3]))    // 0.6000000000000001 (floating point precision issue)
console.log(sum([1.1, 2.2, 3.3]))    // 6.6

Handle Large Numbers

typescript
import { sum } from 'radash'

console.log(sum([1000000, 2000000, 3000000])) // 6000000
console.log(sum([Number.MAX_SAFE_INTEGER, 1])) // 9007199254740992

Handle Mixed Numbers

typescript
import { sum } from 'radash'

console.log(sum([1, 2.5, 3, 4.5, 5])) // 16
console.log(sum([-1, 0, 1, 2]))       // 2
console.log(sum([1, -1, 2, -2]))      // 0

Using with Object Arrays

typescript
import { sum } from 'radash'

const products = [
  { id: 1, name: 'Laptop', price: 999 },
  { id: 2, name: 'Phone', price: 599 },
  { id: 3, name: 'Tablet', price: 399 }
]

const prices = products.map(product => product.price)
const totalPrice = sum(prices)
console.log(totalPrice) // 1997

Calculate Average

typescript
import { sum } from 'radash'

function average(numbers: number[]): number {
  if (numbers.length === 0) return 0
  return sum(numbers) / numbers.length
}

console.log(average([1, 2, 3, 4, 5])) // 3
console.log(average([10, 20, 30]))    // 20
console.log(average([]))               // 0

Calculate Weighted Average

typescript
import { sum } from 'radash'

interface WeightedItem {
  value: number
  weight: number
}

function weightedAverage(items: WeightedItem[]): number {
  if (items.length === 0) return 0
  
  const totalWeight = sum(items.map(item => item.weight))
  const weightedSum = sum(items.map(item => item.value * item.weight))
  
  return totalWeight > 0 ? weightedSum / totalWeight : 0
}

const grades = [
  { value: 85, weight: 0.3 },
  { value: 90, weight: 0.3 },
  { value: 95, weight: 0.4 }
]

console.log(weightedAverage(grades)) // 90.5

Calculate Statistics

typescript
import { sum } from 'radash'

function calculateStats(numbers: number[]) {
  if (numbers.length === 0) {
    return { sum: 0, average: 0, min: 0, max: 0 }
  }
  
  const total = sum(numbers)
  const average = total / numbers.length
  const min = Math.min(...numbers)
  const max = Math.max(...numbers)
  
  return { sum: total, average, min, max }
}

const scores = [85, 92, 78, 96, 88, 90]
const stats = calculateStats(scores)

console.log(stats)
// { sum: 529, average: 88.16666666666667, min: 78, max: 96 }

Process Time Series Data

typescript
import { sum } from 'radash'

interface TimeSeriesPoint {
  timestamp: number
  value: number
}

function calculateTotalValue(data: TimeSeriesPoint[]): number {
  const values = data.map(point => point.value)
  return sum(values)
}

const timeSeriesData = [
  { timestamp: 1000, value: 10 },
  { timestamp: 2000, value: 20 },
  { timestamp: 3000, value: 30 },
  { timestamp: 4000, value: 40 }
]

const total = calculateTotalValue(timeSeriesData)
console.log(total) // 100

Calculate Financial Data

typescript
import { sum } from 'radash'

interface Transaction {
  id: number
  amount: number
  type: 'income' | 'expense'
}

function calculateNetIncome(transactions: Transaction[]): number {
  const incomes = transactions
    .filter(t => t.type === 'income')
    .map(t => t.amount)
  
  const expenses = transactions
    .filter(t => t.type === 'expense')
    .map(t => t.amount)
  
  const totalIncome = sum(incomes)
  const totalExpenses = sum(expenses)
  
  return totalIncome - totalExpenses
}

const transactions: Transaction[] = [
  { id: 1, amount: 1000, type: 'income' },
  { id: 2, amount: 500, type: 'expense' },
  { id: 3, amount: 200, type: 'expense' },
  { id: 4, amount: 300, type: 'income' }
]

const netIncome = calculateNetIncome(transactions)
console.log(netIncome) // 600 (1000 + 300 - 500 - 200)

Handle Nested Arrays

typescript
import { sum } from 'radash'

function sumNestedArrays(arrays: number[][]): number {
  const flattened = arrays.flat()
  return sum(flattened)
}

const nestedArrays = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

const total = sumNestedArrays(nestedArrays)
console.log(total) // 45

Calculate Percentages

typescript
import { sum } from 'radash'

function calculatePercentages(values: number[]): number[] {
  const total = sum(values)
  if (total === 0) return values.map(() => 0)
  
  return values.map(value => (value / total) * 100)
}

const votes = [150, 200, 100, 50]
const percentages = calculatePercentages(votes)

console.log(percentages) // [30, 40, 20, 10]

Process Sales Data

typescript
import { sum } from 'radash'

interface Sale {
  product: string
  quantity: number
  price: number
}

function calculateTotalSales(sales: Sale[]): number {
  const revenues = sales.map(sale => sale.quantity * sale.price)
  return sum(revenues)
}

const sales: Sale[] = [
  { product: 'Laptop', quantity: 2, price: 999 },
  { product: 'Phone', quantity: 3, price: 599 },
  { product: 'Tablet', quantity: 1, price: 399 }
]

const totalSales = calculateTotalSales(sales)
console.log(totalSales) // 4194 (2*999 + 3*599 + 1*399)

Notes

  1. Empty arrays: If the array is empty, returns 0
  2. Floating point precision: Floating point addition may have precision issues
  3. Large numbers: For very large numbers, be aware of JavaScript's number precision limits
  4. Performance: Time complexity is O(n), where n is the array length
  5. Type: Only accepts number arrays, other types will cause errors

Differences from Other Methods

  • reduce(): More flexible but requires providing an accumulation function
  • sum(): Concise method specifically for summation provided by radash
  • Array.prototype.reduce((a, b) => a + b, 0): Same functionality but more verbose

Practical Application Scenarios

  1. Financial calculations: Calculate income, expenses, profits, etc.
  2. Statistical analysis: Calculate sums, averages, and other statistics
  3. Sales analysis: Calculate sales revenue, order totals, etc.
  4. Scoring systems: Calculate total scores, average scores, etc.
  5. Data aggregation: Summarize various numerical data

Released under the MIT License.