Skip to content
Node: arr.reduce(fn, init)github.com/sahilkhaire/gox/slice

Reduce

Overview

Reduce folds the slice (Array.reduce).

If you are coming from Node.js, the closest pattern is arr.reduce(fn, init).

Signature

go
func Reduce[T, U any](in []T, init U, fn func(U, T) U) U

Compare: Node.js · Standard Go · gox

js
const total = nums.reduce((acc, n) => acc + n, 0);
go
total := 0
for _, n := range nums {
    total += n
}
go
import "github.com/sahilkhaire/gox/slice"

total := slice.Reduce(nums, 0, func(acc, n int) int { return acc + n })

Example

go
import "github.com/sahilkhaire/gox/slice"

total := slice.Reduce(nums, 0, func(acc, n int) int { return acc + n })

Tips

Chain Filter, Map, and Reduce for lodash-style pipelines. Results are new slices — inputs are never mutated.

Standard library alternative

Use the standard library directly:

go
total := 0
for _, n := range nums {
    total += n
}

Back to slice package overview

MIT Licensed · Built for Node.js developers moving to Go