
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeThis is indeed a JavaScript question, and you're on the right track! You can use the reduce() method to sum up all the distances from your Sanity posts. Here's how:
const totalDistance = posts.reduce((sum, post) => {
return sum + post.trailHiked.distance;
}, 0);
console.log(totalDistance); // 4.45Or if you prefer a more concise arrow function syntax:
const totalDistance = posts.reduce((sum, post) => sum + post.trailHiked.distance, 0);How it works:
reduce() iterates through each item in your arraysum is the accumulator that keeps track of the running totalpost, you add its trailHiked.distance to the sum0 at the end is the initial value for sumAlternative approaches:
If you're doing this calculation in a GROQ query (Sanity's query language), you could also calculate the sum directly when fetching your data:
{
"posts": *[_type == "post"],
"totalDistance": math::sum(*[_type == "post"].trailHiked.distance)
}This way, Sanity does the calculation for you and returns both your posts and the total distance in one query. This can be more efficient if you're dealing with large datasets since the calculation happens on the server side.
For your specific use case with the growing array, the JavaScript reduce() method is perfect and will automatically handle any number of entries as your array grows!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store