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
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 .reduce body. .reduce lets 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 .reduce callback.
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) {
const sum = people.reduce(function(acc, current) {
return acc + Number(current.balance.replace(/\$|,/g, ""));
}, 0);
return sum / people.length;
}
console.log(averageBalance(people));