How to join array of strings into single comma-separated string in GROQ?

7 replies
Last updated: Jul 27, 2022
Hi all, does anyone know of a way in groq to join an array of strings into a single output string? Sorry if I've missed something obvious!
This query produces an array of strings, but I would like "sectors" to produce a string with a single comma separated list. Thanks as always for the help.

*[_type == "technologyProduct"]{
   "sectors": targetIndustries[]->title,
}
AI Update

Great question! Yes, GROQ has a built-in function for exactly this: array::join().

You can modify your query like this:

*[_type == "technologyProduct"]{
   "sectors": array::join(targetIndustries[]->title, ", "),
}

The array::join() function takes two parameters:

  1. An array of strings, numbers, or booleans
  2. A separator string (in your case ", " for comma-separated)

It returns a single concatenated string.

According to the GROQ Functions Reference, the syntax is:

array::join(source <array[string|number|boolean]>, separator<string>) <string>

So in your case, targetIndustries[]->title produces an array of strings, and array::join() combines them into a single comma-separated string.

Note that if any element in the array isn't a string, number, or boolean, the function will return null. Also, if the input itself isn't an array (like if it's a single value), it will return null as well.

You can find more examples in the Query Cheat Sheet which shows examples like array::join(["a", "b", "c"], ".") returning "a.b.c".

Show original thread
7 replies
Pretty sure it’s not possible.
Thanks Kitty- good to know- I'll work around it!
Maybe these 2 links can help you, but I don’t think you can do so, unless you flatten the array in your front end with
array.toString()
.

https://www.sanity.io/docs/high-performance-groq
https://www.sanity.io/docs/query-cheat-sheet#4ff061cc51e4
Or
array.join(', ')
. 🙂
I think you could also set a patch even with a custom document action and get your array of strings (or however you want it to be saved) patched into another field.
Thanks all. I can work around it on the front end, but I was hoping to shape the data in the query and avoid the need to create another component. Not a major headache!
you don’t need a new component… that’s a quick function you could use for setting the data into a component.

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?