Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
Iterate through an array of objects and calculate one single property value

So let's say we do have this array:

const db = [
{name: 'Coffe', price: '10'},
{name: 'Stackoverflow Stickers', price: '7.5'},
{name: 'Nike Air Force', price: '100'},
// more objects in similar format (long list)
]

So what I want to do is iterate through array and calculate all prices of each object value, in this case price.

What I tried, but somehow it doesn't work works:

let total = 0;
data.map((d) => (d.total += total))
setTotal(totalValues)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the Array.reduce function:

const total = db.reduce(
  (total, curr) => total + parseFloat(curr.price),
  0
);
setTotal(total);

Read more: https://www.w3schools.com/jsref/jsref_reduce.asp

about 4 years ago · Juan Pablo Isaza Report

0

you can use array reduce for this

don't forget to parseFloat your string in db data

const db = [
{name: 'Coffe', price: '10'},
{name: 'Stackoverflow Stickers', price: '7.5'},
{name: 'Nike Air Force', price: '100'},
]

let total = db.reduce((previous, current) => (previous + parseFloat(current.price)), 0)
console.log(total)

about 4 years ago · Juan Pablo Isaza Report

0

Try the below changes to fix the issue. Inside map function instead of (d) => (d.total += total) use (d) => (total+= Number(d.price)).

const data = [
{name: 'Coffe', price: '10'},
{name: 'Stackoverflow Stickers', price: '7.5'},
{name: 'Nike Air Force', price: '100'},
// more objects in similar format (long list)
]

let total = 0;
data.map((d) => (total+= Number(d.price)))
console.log(total)

Note: Instead of using map , use forEach or a normal loop for these kind of operations. Like this:

data.forEach((d) => (total+= Number(d.price)))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!