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

chunk-by for filters

Divides a sequence into sub-sequences based on a closure.

Signature

> chunk-by {flags} (closure)

Parameters

  • closure: The closure to run.

Input/output types:

inputoutput
list<any>list<list<any>>
rangelist<list<any>>

Examples

Chunk data into runs of larger than zero or not.

> [1, 3, -2, -2, 0, 1, 2] | chunk-by {|it| $it >= 0 }
╭───┬────────────╮
│ 0 │ ╭───┬───╮  │
│   │ │ 0 │ 1 │  │
│   │ │ 1 │ 3 │  │
│   │ ╰───┴───╯  │
│ 1 │ ╭───┬────╮ │
│   │ │ 0 │ -2 │ │
│   │ │ 1 │ -2 │ │
│   │ ╰───┴────╯ │
│ 2 │ ╭───┬───╮  │
│   │ │ 0 │ 0 │  │
│   │ │ 1 │ 1 │  │
│   │ │ 2 │ 2 │  │
│   │ ╰───┴───╯  │
╰───┴────────────╯

Identify repetitions in a string

> [a b b c c c] | chunk-by { |it| $it }
╭───┬───────────╮
│ 0 │ ╭───┬───╮ │
│   │ │ 0 │ a │ │
│   │ ╰───┴───╯ │
│ 1 │ ╭───┬───╮ │
│   │ │ 0 │ b │ │
│   │ │ 1 │ b │ │
│   │ ╰───┴───╯ │
│ 2 │ ╭───┬───╮ │
│   │ │ 0 │ c │ │
│   │ │ 1 │ c │ │
│   │ │ 2 │ c │ │
│   │ ╰───┴───╯ │
╰───┴───────────╯

Chunk values of range by predicate

> (0..8) | chunk-by { |it| $it // 3 }
╭───┬───────────╮
│ 0 │ ╭───┬───╮ │
│   │ │ 0 │ 0 │ │
│   │ │ 1 │ 1 │ │
│   │ │ 2 │ 2 │ │
│   │ ╰───┴───╯ │
│ 1 │ ╭───┬───╮ │
│   │ │ 0 │ 3 │ │
│   │ │ 1 │ 4 │ │
│   │ │ 2 │ 5 │ │
│   │ ╰───┴───╯ │
│ 2 │ ╭───┬───╮ │
│   │ │ 0 │ 6 │ │
│   │ │ 1 │ 7 │ │
│   │ │ 2 │ 8 │ │
│   │ ╰───┴───╯ │
╰───┴───────────╯

Notes

chunk-by applies the given closure to each value of the input list, and groups consecutive elements that share the same closure result value into lists.