I'm new to jq,
and would like to get the intersection of two arrays (similar question BUT with different approach: link). I managed to get the union of two arrays and addition of two arrays: i.e:
A=['a','b','e','c']
B=['g','a','t','c']
I have wrote:
echo '{"group_a":["A","B","C","ABC"],"group_b":["B","D"]}' | jq .group_a+.group_b
A+B = ['a','b','e','c','g','g','a','t','c']
echo '{"group_a":["A","B","C","ABC"],"group_b":["B","D"]}' | jq .group_a+.group_b | jq 'unique'
A U B = ['a','b','e','c','g','t']
but how do i now apply this simple logic:
intersection = unique((A+B) - (A U B))
i'm used to one liners, and I'd like this snippet to be readable and elegant for future use. so how do i implement this in jq style?
any assistance will be helpful, Thank you all!
Assuming arrays do not contain duplicates (if they do, use unique
to filter out duplicate results):
jq -cn '["a","b","e","c"] as $A | ["g","a","t","c"] as $B | $A - ($A - $B)'
echo '{ "group_a" : ["a","b","e","c"], "group_b" : ["g","a","t","c"] }' |
jq -c '.group_a - (.group_a - .group_b)'
They both yield:
["a","c"]