How can I find the average of an object(number) using function forEach?
var people =[{
name = "John"
number = "283.37"
},{
name = "Susan"
number = "125,44"
},{
name = "Karen"
number = "98,7"
}];
var sum = 0;
people.forEach(function(num) { sum += num});
average = sum / people.length;
console.log(average);
I get the Nan error
You have some syntax issues in your object literal. And then you must first convert your number
prop to something that can be added. I use parseFloat() to make number from string.
var people = [{
name:"John",
number:"283.37"
}, {
name: "Susan",
number: "125,44"
}, {
name:"Karen",
number: "98,7"
}];
var sum = 0;
people.forEach(function(item) {
sum += parseFloat(item.number);
});
average = sum / people.length;
console.log(average);
Or you can do this with Array.reduce():
var people = [{
name:"John",
number:"283.37"
}, {
name: "Susan",
number: "125,44"
}, {
name:"Karen",
number: "98,7"
}];
const average = people.reduce((a, b) => (a + parseFloat(b.number)), 0) / people.length;
console.log(average);