Everything *[NYC] 2026: see what we announced. →

Alphabetizing Flattened Nested Arrays of Strings

When each document queries has an array but you need the aggregate list to be ordered.

By Vincent Florio


Fetching first name array for all people documents

*[_type == "people"].listOfNames

Flatten all 'people' documents' first names into an unsorted list

*[_type == "people"].firstNames[]

Sort the entire list of strings based solely on their value

*[_type == "people"].firstNames[] | order(@)

It's true that when working with GROQ queries in Sanity you can easily sort an array of strings by way of the order() function.

You may, however, be unsure how to sort the entire list in aggregate, across all documents, since you will no longer have keys or prop names to sort by.

This snippet demonstrates a simple yet effective way to achieve this, ensuring the flattened array is both combined and alphabetically ordered.

Start with a Basic Query

Suppose you have a document type people where each document contains an array firstNames.

Your initial query might look like this:

*[_type == "people"].listOfNames

This query will return an array of arrays, such as

[ ["Bob", "Jessica", "Steve"], ["Alfonso", "Will", "Patricia"] ]

Flatten the Array:

To combine these into a single array, modify the query by appending [] to firstNames, e.g.

*[_type == "people"].firstNames[]

This alteration flattens the arrays, resulting in:

["Bob", "Jessica", "Steve", "Alfonso", "Will", "Patricia"]

Sort the Flattened Array Alphabetically:

This is where the magic happens! To sort the entire flattened array, you can use the order() function applied to each element using the @ symbol, which in GROQ refers to the root value of the current scope, block or projection. It should now look like this:

*[_type == "people"].firstNames[] | order(@)

Simply adding order(@) to the end of your query ensures that the elements of the flattened array are sorted alphabetically:

["Alfonso", "Bob", "Jessica", "Patricia", "Steve", "Will"]

Contributor

Vincent Florio

Vincent Florio

Finding satisfaction in newly achievable creative challenges

United States

Visit Vincent Florio's profile