Comparing arrays in GROQ query to find intersections.

4 replies
Last updated: Feb 28, 2024
Can someone help me with line 5 - I'm trying to compare two arrays, one is the field allCheckinIds (an array of strings) and the other is a variable $userIds (also an array of strings). I'm trying to see whether there are at least one "intersection" between them.
AI Update

For checking if two arrays have at least one intersection (overlapping value), you can use the count() function combined with the @ filter operator in GROQ. Here's the pattern:

count(array1[@ in array2]) > 0

So if you have a field allCheckinIds and a parameter $userIds, you'd write:

count(allCheckinIds[@ in $userIds]) > 0

This works by:

  1. Taking the first array (allCheckinIds)
  2. Filtering it with [@ in $userIds] - the @ represents each element in the array, and checks if it exists in the second array
  3. Counting how many matches were found
  4. Checking if that count is greater than 0

You can use this in a filter to find documents that have at least one matching value:

*[_type == "yourType" && count(allCheckinIds[@ in $userIds]) > 0]

This is a clever workaround since GROQ doesn't have a built-in array intersection operator. The technique comes from this community discussion where the same question was asked.

If you need to pass userIds as a parameter (which is common when querying from your application), you'd use it like this with the JS client:

client.fetch(
  `*[_type == "yourType" && count(allCheckinIds[@ in $userIds]) > 0]`,
  { userIds: ['id1', 'id2', 'id3'] }
)
function checkIntersection(array1, array2) {
    return array1.some(item => array2.includes(item));
}
Not sure if you mean something like this
Correct, but I would like to do it in the GROQ-query itself.
Comparing two arrays will require syntax like seen here , which uses the
count()
function and the parent operator. Presumably, it’ll be something like:

checkinId in $userIds ||
count((allCheckinIds[])[@ in $userIds]) > 0
Great, thank you so much!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?