Skip to content

Support sub-record keys and closures in group-by/sort-by #8322

Closed

Description

@mon-jai

Related problem

It is not easy to group/sort data with sub-keys.

Consider the following data structure storing Twitter tweets.

let tweets = [
  {
    "author": { 
      "id": 1,
      "username": "mon-jai"
    },
    "created": 1677877558
    "caption": "Hello world",
    "comments": [{}, {}, {}]
  },
  # ...
]

In today's Nushell,

What if I want to group tweets by author?

$tweets | each {|$it| insert author_username { $it | get author.username } } | group-by author_username

What if I want to sort tweets by comments count?

$tweets | each {|$it| insert comments_count { $it | get comments | length } } | sort-by comments_count

The solution requires us to process the data beforehand and is not straight forward.

Describe the solution you'd like

By supporting sub-record keys and closures in group-by/sort-by, we can process the data more conveniently.

Sub-record keys

$tweets | group-by author.username

Closures

$tweets | sort-by { get comments | length }

Describe alternatives you've considered

No response

Additional context and details

No response

Activity

  1. added
    category:enhancement
    on Mar 5, 2023
  2. sholderbach commented on Mar 6, 2023

    @sholderbach
    Member

    Interesting point!

    For reference to the interested parties. In the nushell code base the "sub-record keys" are referred to as "cell paths".

  3. cablehead commented on Mar 13, 2024

    @cablehead
    Contributor

    Noting additional interest in this issue, from the discord help channel

  4. cablehead commented on Apr 24, 2024

    @cablehead
    Contributor

    From Steve on discord:

    How do i best sort a list of strings by length? I came up with:
    
    echo [Steve,Alice,Charles, Bob] | each { |x| [[name,len]; [$x ,($x | str length)]] } | flatten | sort-by len | get name
    
    but that's a bit unwieldy. Can sort-by somehow take a closure?
    
  5. weirdan commented on Feb 10, 2026

    @weirdan
    Contributor

    All the features requested here are already implemented (tested on 0.110.0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

category:enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions