13

i have a layer that i want to filter by multiple values stored in array

let filter = ['in','id', 1,2,3]
map.setFilter('layer_name',filter)

this works fine and it will return only features with ID 1,2,3 but in Mapbox GL specs, they label this in expression as deprecated https://www.mapbox.com/mapbox-gl-js/style-spec/#other-filter and encourage using the new expressions, i think the expression match would work but don't know know it should look like, i tried to do like

['match', 'get', 'id', 1,2,3 ];

it's not really that clear in the Docs so if anyone can clarify it please

1 Answer 1

16

Yes, the match expression works, it should look like:

let filter = ['match', ['get', 'id'], [1, 2, 3], true, false]
map.setFilter('layer_name',filter)

Update:

Since Mapbox GL JS v1.6.0, there's an in expression. It can check if a value is in an array:

['in', ['get', 'id'], ['literal', [1, 2, 3]]]
5
  • thank you it works fine, but can you explain a bit what is the true , false for ?! i understand what the rest is for Jun 27, 2018 at 5:40
  • 1
    true/false are the output values, from the docs: "Selects the output whose label value matches the input value, or the fallback value if no match is found." false is the fallback value in this case.
    – pathmapper
    Jun 27, 2018 at 5:53
  • so in other words the filter would be " get the id field and match it for those [1,2,3] then if true return the feature matched, otherwise don't " thanks, i think i got my head around it Jun 27, 2018 at 6:00
  • 3
    it's more "get the id field, if it matches a value of [1,2,3] return true, otherwise false"
    – pathmapper
    Jun 27, 2018 at 6:12
  • Great it works perfectly for me. Jul 12, 2022 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.