sum of numbers in array not working
Clash Royale CLAN TAG#URR8PPP
sum of numbers in array not working
I have some array like this:
state =
array: [
id1,
name1,
price1
,
id2,
name2,
price2
,
id3,
name3,
price3
]
and then I'm trying to sum the prices.
First I tried -
for (let key in arrayCopy)
totals += this.state.array[key].price;
2nd I've tried =
for (let key in arrayCopy)
total[key] = this.state.array[key].price;
var totals = total.reduce((a,b) => a + b,0);
I will try to explain it with numbers. For example:
price1 = 1000
price2 = 2000
price3 = 5000
I'm trying to get the total result by summing all the prices.
totals = price1 + price2 + price3
totals = 8000
but the result that I got is:
totals = 100020005000
Can someone please point out what I did wrong?
price1
price2
this.state.array[key].price;
2 Answers
2
It is because your price
is a string
rather than a number
, you will need to convert it to number first.
price
string
number
var totals = this.state.array.reduce((a,b)=>a+Number(b), 0);
@torazaburo sense :)
– Sabrina Luo
Aug 7 at 7:02
items: [
id1,
name1,
price
,
id2,
name2,
price
,
id3,
name3,
price
]
let sum = null; // Place to store the total cost
// The JavaScript Array.prototype specifies a built-in method called
// forEach that takes a function as an argument. That function is
// automatically passed 3 arguments and is executed for each element
// in the array.
items.forEach(function(value, index, arry)
sum += value.price;
);
console.log(sum);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you have
price1
,price2
..and you are accessingthis.state.array[key].price;
? what are you trying to achieve ?– Aravind S
Aug 7 at 5:40