Sum distances from nested trailHiked objects in Sanity posts array

1 replies
Last updated: Mar 30, 2022
I know this is more of a basic js question but I have an array of objects (my sanity posts), that all have a field of an object called trailHiked and all have a distance. I'm trying to create a variable that would calculate the sum of all the distances in my array (the array will continue to get more entries).
 [
  {
    number: 1,
    trailHiked: { distance: 1.67, name: 'Saugus River Trail', rating: 4 }
  },
  {
    number: 2,
    trailHiked: { distance: 1.48, name: 'Great Woods Path', rating: 5 }
  },{
    number: 3,
    trailHiked: { distance: 1.3, name: 'Cross Fells Trail and Half Mile Road', rating: 5
    }
  },
]
AI Update

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.45

Or 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 array
  • sum is the accumulator that keeps track of the running total
  • For each post, you add its trailHiked.distance to the sum
  • The 0 at the end is the initial value for sum

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 thread
1 reply
Try a
reduce()
πŸ™‚
Here
total
defaults to
0
, and for each item in the array, the value of
item.trailHiked.distance
is added.

const totalDistance = data.reduce((total, item) => total + item.trailHiked.distance, 0)

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?