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)
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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)))