πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

How to Calculate the Sum of All the Distances in an 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
    }
  },
]
Mar 29, 2022, 11:42 PM
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)
Mar 30, 2022, 5:21 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?