JQ:两个数组的setdiff

JQ: setdiff of two arrays

如果我有一个包含两个包含唯一值的数组的对象

{"all":["A","B","C","ABC"],"some":["B","C"]}

如何找到 .all - .some

在这种情况下,我正在寻找 ["A","ABC"]

@Jeff Mercado 让我大吃一惊!我不知道数组减法是允许的...

echo -n '{"all":["A","B","C","ABC"],"some":["B","C"]}' | jq '.all-.some'

产量

[
  "A",
  "ABC"
]

我一直在寻找类似的解决方案,但要求动态生成数组。下面的解决方案只是做了预期的

array1=$(jq -e '')  // jq expression goes here
array2=$(jq -e '')  // jq expression goes here

array_diff=$(jq -n --argjson array1 "$array1" --argjson array2 "$array2" 
'{"all": $array1,"some":$array2} | .all-.some' )

同时 - Array Subtraction is the best approach for this, here is another solution using del and indices:

. as $d | .all | del(.[ indices($d.some[])[] ])

当您想知道删除了哪些元素时,它可能会有所帮助。例如,对于示例数据和 -c(紧凑输出)选项,以下过滤器

  . as $d
| .all
| [indices($d.some[])[]] as $found
| del(.[ $found[] ])
| "all", $d.all, "some", $d.some, "removing indices", $found, "result", .

产生

"all"
["A","B","C","ABC"]
"some"
["B","C"]
"removing indices"
[1,2]
"result"
["A","ABC"]