tekumara
tekumara

Reputation: 8807

sort by element in array using jq

Given

[3,4]
[5,2]

I'd like to produce:

[5,2]
[3,4]

I tried this but it fails:

echo '[3,4] [5,2]' | jq 'sort_by(.[1])'

jq: error (at <stdin>:1): Cannot index number with number
jq: error (at <stdin>:1): Cannot index number with number

Upvotes: 2

Views: 239

Answers (1)

pmf
pmf

Reputation: 36033

Use -n with inputs to access the stream's items. [‌...] collects them into an outer array, sort_by(...) sorts by criteria, ...[] decomposes the outer array again, and -c makes the output compact

jq -nc '[inputs] | sort_by(.[1])[]'
[5,2]
[3,4]

Demo

Upvotes: 6

Related Questions