Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document how sort_by() can sort by multiple keys, including an example. #2474

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/content/manual/manual.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1368,13 +1368,21 @@ sections:
`sort_by(foo)` compares two elements by comparing the result of
`foo` on each element.

Also note that `sort_by(.k1, .k2, .k3, ...)` behaves as you would
expect: it sorts first by comparing elements by key `k1`, then
comparing elements by key `k2` to "break ties" left by `k1`,
then comparing elements by key `k3`, and so on.

examples:
- program: 'sort'
input: '[8,3,null,6]'
output: ['[null,3,6,8]']
- program: 'sort_by(.foo)'
input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'
output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']
- program: 'sort_by(.foo, .bar)'
input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}, {"foo":3, "bar":200}]'
output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":3, "bar":200}, {"foo":4, "bar":10}]']
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The input value can be improved by flipping the foo:3 elements to make it clear the program sorts by bar (program sort_by(.foo) yields the same output currently).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW, it would also be great to have another complicated example where the keys have transformations. For example:

$ echo '[{"foo":"20", "bar":10}, {"foo":"3", "bar":100}, {"foo":"2", "bar":1}, {"foo":"3", "bar":200}]' | jq '. | sort_by([.foo | tonumber], .bar)'
[
  {
    "foo": "2",
    "bar": 1
  },
  {
    "foo": "3",
    "bar": 100
  },
  {
    "foo": "3",
    "bar": 200
  },
  {
    "foo": "20",
    "bar": 10
  }
]

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@php-coder I think such a complicated example with filter combination can be listed in the Cookbook, and actually there is an example using sort_by with tonumber. You can freely edit the wiki page if this example is not enough. BTW I think there should be an example for version sorting. Thanks.


- title: "`group_by(path_expression)`"
body: |
Expand Down