🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Quick and easy way to count images in GROQ arrays for article teasers.

2 replies
Last updated: Sep 7, 2023
Is there a quick and easy way to count all images in an array of content blocks in GROQ? I’m adding a small text summary like
12 minute read and 43 images
to article teasers. Managed to handle word count no problem, just thinking about a query for counting images. I have a few different content blocks with images, so I assume the query might be complex
Sep 7, 2023, 5:14 AM
I’ve written this query, which works, but seems like it might be over complicated:

"imageCount": math::sum(
  content[] {
    "count": 0,
    _type == "imageBlock" => {
      "count": 1, 
    _type in ["imageGalleryBlock", "inlineImagesBlock"] => {
      "count": length(images[]),
I’ll stick with this for now, but could there be any more elegant implementations?
Sep 7, 2023, 5:27 AM
Not sure if more elegant, but:
count(content[_type == "imageBlock"])
+ math::sum(
    content[_type in "imageGalleryBlock", "inlineImagesBlock"] {
      "count": count(images)
Would be simpler if we had a flatten function, but we don't yet.
Sep 7, 2023, 9:22 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?