【问题标题】:JQ: setdiff of two arraysJQ:两个数组的setdiff
【发布时间】:2015-06-06 09:59:53
【问题描述】:

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

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

如何找到.all - .some

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

【问题讨论】:

  • 您还没有想要的东西吗? .all - .some

标签: jq set-difference


【解决方案1】:

虽然- Array Subtraction 是解决此问题的最佳方法,但这是使用delindices 的另一种解决方案:

. 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"]

【讨论】:

    【解决方案2】:

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

    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' )
    

    【讨论】:

    • 你可以在最后做$array1-$array2
    【解决方案3】:

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

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

    产量

    [
      "A",
      "ABC"
    ]
    

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      相关资源
      最近更新 更多