Cumulative sum in jq -
i have series of [timestamp, count] pairs in array , want compute cumulative sum @ each timestamp using jq. how that?
here sample data set:
[ [1431047957699, 1], [1431047958269, 1], [1431047958901, 1], [1431047959147, -1], [1431047960164, 1] ] and expected result:
[1431047957699, 1], [1431047958269, 2], [1431047958901, 3], [1431047959147, 2], [1431047960164, 3] is possible jq?
the following quite general (e.g. can used array of objects):
def accumulate(f): reduce .[1:][] $row ([.[0]]; . $x | $x + [ $row | (f = ($x | .[length-1] | f) + ($row|f) ) ] ); accumulate(.[1]) if using sufficiently recent version of jq, "$x | .[length-1]" can simplified "$x[-1]".
solution using foreach
if jq has foreach, following variant can used. particularly appropriate if stream of values rather array wanted.
def accumulates(f): foreach .[] $row (0; . + ($row | f) ; . $x | $row | (f = $x)); usage:
for stream: accumulates(.[0])
for array: [accumulates(.[0])
Comments
Post a Comment