Filter Arrays in JSON Based on Other Arrays in GROQ

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

We can also use GROQ's in keyword in our filters and negate it using the !() syntax. This allows us to exclude items that might be included later on in joins before we even get to the projection stage of our query. This example demonstrates filtering out all of the evolutions of Pokemon since they will be included by joining them into the base Pokemon objects.

John Lindquist: [0:00] Right now, our data has each base Pokemon with its evolutions. Then, that evolution is still listed here with a single evolution, and then the final evolution with no evolutions. We can actually filter out these evolutions so that they're only listed under the base evolution, by doing the same logic we did here.

[0:22] I'm just going to copy this and wrap it in parens, with an exclamation point in front, and then paste it here. Instead of looking at the parent scope, we'll again look at the root scope. Now we're filtering out every num that is found in a nextEvolution, before we even get to this.

[0:46] If I run this now, you'll see the result as being Bulbasaur with its two evolutions. Then, neither of those evolutions, Ivysaur and Venusaur, those are both gone. Then, Charmander has its evolutions, but its evolutions aren't listed down here.

[1:02] You can use this IN syntax to filter out by using the exclamation point and wrapping that expression there in parens. We're able to filter out every Pokemon we don't want to look at before we even get to this next part of our query, where we then can look through the root scope again and find those next evolutions.

[1:24] These IN statements become super powerful for either joining data or excluding data, based on how these nums, or usually IDs, or types, or anything, match up.