Artem Trunov
Artem Trunov

Reputation: 1415

jq select record from array with min or max value of field

I have a json with records like this:

[
 {"number":1},
 {"number":3}
]

and want to select (filter) a record with a max or min value of the field "number".

I can get a min or max value of "number" like this:

$ echo '[{"number":1},{"number":3}]' | jq ' [ .[].number ] | min'

(emits 1)

and I can output booleans:

$ echo '[{"number":1},{"number":3}]' | jq '.[].number==([ .[].number ] | min)'
true
false

but when I try to put that together with select, it fails:

$ echo '[{"number":1},{"number":3}]' | jq 'map(select(.[].number==([ .[].number ] | min)))'
jq: error (at <stdin>:1): Cannot index number with string "number"

I feel like I am close, but stuck. What am I doing wrong?

Thanks in advance!

Upvotes: 4

Views: 4644

Answers (1)

peak
peak

Reputation: 116780

([ .[].number ] | min) as $m| map(select(.number== $m))

See https://jqplay.org/s/bUwtNrfAE-

first

To retrieve the first minimal item:

([ .[].number ] | min) as $m| first(.[]|select(.number== $m))

min_by, minimal_by, etc

jq has the built-ins max_by and min_by, as documented at https://stedolan.github.io/jq/manual/#Builtinoperatorsandfunctions

For a definition of maximal_by, see the jq cookbook at https://github.com/stedolan/jq/wiki/Cookbook#find-the-maximal-elements-of-an-array-or-stream. That section also has stream-oriented definitions.

Upvotes: 9

Related Questions