Search code examples
arraysjsonjqsubtractionblacklist

JQ — Remove elements by value not index


I need to delete all elements of instances that are either set to "three" or "five". Their index is not always the same:

{
"address": "localhost",
"name": "local",
"vars": {
    "instances": [
        "one",
        "two",
        "three",
        "four",
        "five"
    ]
  }
}

Solution

  • Suppose you have:

    [10, 10, 20, 10, 20, 10, 30]
    

    …and you want to remove all the 20 and all the 30. Here's one way:

    . - [20, 30]
    

    As well as normal arithmetic subtraction on numbers, the - operator can be used on arrays to remove all occurrences of the second array's elements from the first array.

    See https://stedolan.github.io/jq/manual/#Builtinoperatorsandfunctions

    In your case you could do:

    .vars.instances -= ["three", "five"]
    

    …which returns:

    {
      "address": "localhost",
      "name": "local",
      "vars": {
        "instances": [
          "one",
          "two",
          "four"
        ]
      }
    }