Skip to content
Latchkey

jq sort_by, min_by and max_by : Order and Pick

jq sort_by(f) returns the input array sorted ascending by f, while max_by(f) and min_by(f) return the single element with the largest or smallest f.

Sorting an API array before taking the first or last element, or picking the extreme directly with max_by, is how you grab the newest tag or largest artifact in CI.

What it does

sort_by(f) evaluates f for each element and returns a new array ordered ascending by that value; append reverse for descending. max_by(f) returns the whole element with the maximum f and min_by(f) the minimum, both null on an empty array. Plain sort, min, and max work on the elements themselves rather than a derived key.

Common usage

Terminal
# newest first by created date
jq 'sort_by(.created_at) | reverse' runs.json
# the most recent run object directly
jq 'max_by(.created_at)' runs.json
# pick the latest after sorting
jq 'sort_by(.created_at) | last | .name' runs.json
# smallest of bare numbers
echo '[5,2,9,1]' | jq 'min'

Functions

FunctionWhat it does
sort_by(f)Ascending sort by f
max_by(f) / min_by(f)Element with the largest/smallest f
sort / max / minOperate on the elements themselves
reverseReverse the array (chain for descending)
first / lastTake the first or last element

Common errors in CI

"jq: error: number (5) and string (\"x\") cannot be compared" means f returns mixed types across elements; normalize with tostring or tonumber. "jq: error: null and number cannot be compared" means f is null on some items; filter or default with (.field // 0) before sorting. max_by/min_by return null on an empty array, so guard before indexing.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →