I'm trying to utilize this code to return the average customer balance without the dollar sign or comma. I'm using .reduce because I feel like that's the best option here. Additionally, I'm trying out parseFloat for the first time so I'm just not sure I'm using it correctly. The objective here is
- convert string to number and replace dollar sign and comma with nothing
- sum all the balances
- return the average balance
- use .reduce
var people = [
{
name: "Courtney",
age: 43,
balance: "$3,400"
},
{
name: "Regina",
age: 53,
balance: "$4,000"
},
{
name: "Jay",
age: 28,
balance: "$3,000"
},
]
var averageBalance = function(array){
var average = people.reduce(function(acc, current, index, array){
if(index === array.length - 1){
return acc / array.length;
}
return acc += parseFloat(current.balance.replace(/\$|,/g, ""));
}, 0);
return average;
}
You're trying to do too much inside your
.reducebody..reducelets you do something to every element of an array - such as add them all up. If you want to do one thing separately (like divide by the length of the array to get the average), that should be put outside the.reducecallback.