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

Ibrahim Mohammed
  • 389
  • 1
  • 3
  • 14

1 Answers1

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]]]
pathmapper
  • 1,985
  • 14
  • 22
  • thank you it works fine, but can you explain a bit what is the true , false for ?! i understand what the rest is for – Ibrahim Mohammed Jun 27 '18 at 05: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 '18 at 05: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 – Ibrahim Mohammed Jun 27 '18 at 06: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 '18 at 06:12
  • Great it works perfectly for me. – Khurshid Ansari Jul 12 '22 at 09:56