Nushell
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
GitHub
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
GitHub
  • Categories

    • Bits
    • Bytes
    • Chart
    • Conversions
    • Core
    • Database
    • Dataframe
    • Dataframe Or Lazyframe
    • Date
    • Debug
    • Default
    • Env
    • Experimental
    • Expression
    • Filesystem
    • Filters
    • Formats
    • Generators
    • Hash
    • History
    • Lazyframe
    • Math
    • Misc
    • Network
    • Path
    • Platform
    • Plugin
    • Prompt
    • Random
    • Removed
    • Shells
    • Strings
    • System
    • Viewers

reduce for filters

Aggregate a list (starting from the left) to a single value using an accumulator closure.

Signature

> reduce {flags} (closure)

Flags

  • --fold, -f {any}: reduce with initial value

Parameters

  • closure: Reducing function.

Input/output types:

inputoutput
list<any>any
tableany
rangeany

Examples

Sum values of a list (same as 'math sum')

> [ 1 2 3 4 ] | reduce {|it, acc| $it + $acc }
10

reduce accumulates value from left to right, equivalent to (((1 - 2) - 3) - 4).

> [ 1 2 3 4 ] | reduce {|it, acc| $acc - $it }
-8

Sum values of a list, plus their indexes

> [ 8 7 6 ] | enumerate | reduce --fold 0 {|it, acc| $acc + $it.item + $it.index }
24

Sum values with a starting value (fold)

> [ 1 2 3 4 ] | reduce --fold 10 {|it, acc| $acc + $it }
20

Iteratively perform string replace (from left to right): 'foobar' -> 'bazbar' -> 'quuxbar'

> [[foo baz] [baz quux]] | reduce --fold "foobar" {|it, acc| $acc | str replace $it.0 $it.1}
quuxbar

Replace selected characters in a string with 'X'

> [ i o t ] | reduce --fold "Arthur, King of the Britons" {|it, acc| $acc | str replace --all $it "X" }
ArXhur, KXng Xf Xhe BrXXXns

Add ascending numbers to each of the filenames, and join with semicolons.

> ['foo.gz', 'bar.gz', 'baz.gz'] | enumerate | reduce --fold '' {|str all| $"($all)(if $str.index != 0 {'; '})($str.index + 1)-($str.item)" }
1-foo.gz; 2-bar.gz; 3-baz.gz

Concatenate a string with itself, using a range to determine the number of times.

> let s = "Str"; 0..2 | reduce --fold '' {|it, acc| $acc + $s}
StrStrStr

Merge multiple records together, making use of the fact that the accumulated value is also supplied as pipeline input to the closure.

> [{a: 1} {b: 2} {c: 3}] | reduce {|it| merge $it}
╭───┬───╮
│ a │ 1 │
│ b │ 2 │
│ c │ 3 │
╰───┴───╯