Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding average using function forEach

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading