Home Explore Blog CI



nushell

commands/docs/chunk-by.md
9709750d6b69e29c29ac0e4e85c0108f6f409706e355ad1a0000000300000bab
---
title: chunk-by
categories: |
  filters
version: 0.104.0
filters: |
  Divides a sequence into sub-sequences based on a closure.
usage: |
  Divides a sequence into sub-sequences based on a closure.
editLink: false
contributors: false
---
<!-- This file is automatically generated. Please edit the command in https://github.com/nushell/nushell instead. -->

# `chunk-by` for [filters](/commands/categories/filters.md)

<div class='command-title'>Divides a sequence into sub-sequences based on a closure.</div>

## Signature

```> chunk-by {flags} (closure)```

## Parameters

 -  `closure`: The closure to run.


## Input/output types:

| input     | output          |
| --------- | --------------- |
| list\<any\> | list\<list\<any\>\> |
| range     | list\<list\<any\>\> |
## Examples

Chunk data into runs of larger than zero or not.
```nu
> [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
```nu
> [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
```nu
> (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.

Chunks
526c7bed (1st chunk of `commands/docs/chunk-by.md`)
Title: chunk-by Command Documentation
Summary
This document describes the `chunk-by` command, a filter in Nushell that divides a sequence (list or range) into sub-sequences based on the result of a closure applied to each element. The output is a list of lists, where each sub-list contains consecutive elements that produce the same result when passed to the closure. Examples demonstrate grouping numbers by sign, identifying repetitions in strings, and chunking ranges based on a predicate.