I want to combine consecutive integers in a sorted array and replace them with ranges using jq.
example 1
input:
[1,2,3,4,6,98,99,101]
desired output:"1-4,6,98-99,101"
example 2
input:
[1,3,5]
desired output:"1,3,5"
example 3
input:
[1,2,3,4,5]
desired output:"1-5"
I have found a solution using foreach, but it does not seem very elegant and compact to me.
Is there a simpler solution for this task?
[foreach (.[], 99999) as $current
({};
if length == 0 then
{first: $current}
elif (has("last") | not) and .first + 1 != $current then
{first: $current, extract: "\(.first)"}
elif has("last") and .last + 1 != $current then
{first: $current, extract: "\(.first)-\(.last)"}
else
{first, last: $current}
end;
.extract // empty
)]
| join(",")