Sum distances from nested trailHiked objects in Sanity posts array
This 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 arraysumis the accumulator that keeps track of the running total- For each
post, you add itstrailHiked.distanceto the sum - The
0at the end is the initial value forsum
Alternative 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!
Show original thread1 reply
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.