Skip to content

How to reduce similar elements of array #2105

Answered by mikefarah
dparmar asked this question in Q&A
Discussion options

You must be logged in to vote

This was a fun one - but it did require a nested reduce. I've got the answer in a .yq file so that I can comment on what's happening:

sum_samples.yq

#!./yq

.[] as $i ireduce({}; # reduce over each entry, into a new map
    .[$i.name].name = $i.name |  # set the name to the $i entry

    .[$i.name].sample |= ( # update the sample by looping over each $i sample and adding it
        ($i.sample | to_entries[]) as $k ireduce(.; .[$k.key] += $k.value)
    )

) | [.[]] # convert the map into an array of its values

Then you can run it:

./sum.yq data1.yaml

See reduce for more info.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by dparmar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants