GROQ: Using string comparison shorthand within array::join function

1 replies
Last updated: Jun 20, 2023
Hey folks!
I’m wondering if it is possible to somehow achieve the same result as a short-hand string compare using GROQ within an
array::join
function like this:

*[_id in [$published, $draft]] {
  "slug": "/" + array::join(
    array::compact([
      language=="en" ? null : language,
      parent->parent->slug.current,
      parent->slug.current,
      slug.current
    ]), "/"
  )
}
AI Update

Yes, absolutely! Your current approach with the ternary operator (language=="en" ? null : language) works perfectly fine within array::join(), but you can also achieve the same result using the select() function if you prefer that style.

Your current code is totally valid and quite readable:

*[_id in [$published, $draft]] {
  "slug": "/" + array::join(
    array::compact([
      language=="en" ? null : language,
      parent->parent->slug.current,
      parent->slug.current,
      slug.current
    ]), "/"
  )
}

If you wanted to use select() instead, it would look like this:

*[_id in [$published, $draft]] {
  "slug": "/" + array::join(
    array::compact([
      select(language == "en" => null, language),
      parent->parent->slug.current,
      parent->slug.current,
      slug.current
    ]), "/"
  )
}

Both approaches work identically. The select() function evaluates conditions in order and returns the value of the first condition that evaluates to true, or the fallback value (in this case, language) if no conditions match.

Which should you use? It's mostly a matter of preference:

  • Ternary operator (condition ? value : fallback) is more concise for simple true/false checks
  • select() function shines when you have multiple conditions to check, as it reads more like a switch statement

For your specific use case with a single condition, the ternary operator you're already using is perfectly fine and arguably more readable. The combination with array::compact() elegantly removes the null values for English language slugs, giving you clean URL paths.

Show original thread
1 reply
Resolved it like this, but it’s not the most elegant solution. Much appreciated if someone has a better one to share.
Basically re-querying the same document twice with the conditional within the query.


*[_id in [$published, $draft]] {
  "slug": "/" + array::join(
    array::compact([
      *[language=="en" && _id in [$published, $draft]][0].slug.current,
      parent->parent->slug.current,
      parent->slug.current,
      slug.current
    ]), "/"
  )
}

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?