1
votes

Let's say I have the following:

jq 'map(select(. >= 5))'

given [1,2,3,4,5,6,7] it returns:

[5,6,7]

I also have

jq 'map(select(. < 5))'

which given the same data, returns [1,2,3,4]. How can I do these complementary queries at the same time, so that I receive for example:

[1,2,3,4], [5,6,7]
2

2 Answers

3
votes

jq has a built-in filter for grouping by some (possibly multi-valued) criterion:

jq -nc '[1,2,3,4,5,6,7] | group_by(. < 5)'

produces:

[[5,6,7],[1,2,3,4]]
2
votes

One option is to use reduce:

reduce .[] as $x
([]; if $x < 5 then .[0] += [$x] else .[1] += [$x] end)

This will produce:

[[1,2,3,4],[5,6,7]]