KINDERAS.COM

Fri Jun 17 2022

Comparing arrays in Sanity using groq

This article demos how to compare two array using groq queries in Sanity. This might be useful if you for example need to fetch articles with tags that overlap with a user specified list of tags.

Let's say that we have a document with some tags:

{
  "name": "myDocument",
  //... more stuff
  "tags": ["tag1","tag2", "tag3", "...so on"]
}

Now you want to pass in a list of tags, and if a document has any of them, you want to return the document. Let's say we want only ["tag1","tag3"].

The query would be something like this:

*[_type == "myDocument" && count((tags[])[@ in $inputArray]) > 0]

Where `tags` is the field from the document and the `$inputArray` is the array you pass in the filter on. What's happening here is that we iterate over the tags array and for each item checks if it exists in the inputArray. If this operation returns one or more documents, the query succeeds.

Tip: If you store objects in the arrays you can refer to then like so: tags[].myProp