0

I am trying to write a function that calculates the average student age in a list of student objects, but when I run the code the function prints NaN as an output

function average_age(){
    let total = 0;
    students.forEach(s => {
        total += Number(s.age);
    });
    return  total/size
}
console.log("Average age is : " + average_age())

this is how i constructed the array ( i got the input from the user)

const size = 5
let students = [size]

for (let i=1; i<=5; i++){
    let name = prompt("Enter student's name: ")
    let gender = prompt ("Enter student's gender: ")

    students.push({
        name: name,
        gender: gender,
        age:Math.round(Math.random() * (35 - 17 + 1) + 1),
        grade:Math.round(Math.random() * (100 + 1))
    })
}

//display student info
students.map(s =>{
    console.log("Name: " + s.name);
    console.log("gender: " + s.gender);
    console.log("age: " + s.age);
    console.log("grade: " + s.grade);
    console.log();
})

i tried to calculate the total of student age (removing the divide operation) to check if the problem was the division but i still got NaN as an output

aksak
  • 3
  • 5
  • Can't do much without seeing the rest of your code. Where is the `students` array coming from and are you sure it has all and only numbers in it? – WesleyAC Feb 25 '22 at 15:50
  • where is `average_age()` – cmgchess Feb 25 '22 at 15:50
  • 1
    Nice try, but we still need more info. We cannot copy and paste this code and make it work ans there are parts of the code not written, so impossible to know what is happening. We can just assume. I'm assuming that `s.age` not always has a number there. – Jorge Fuentes González Feb 25 '22 at 15:50
  • Most probably s.age is not a Number. Try : total += Number(s.age) – Endre Szabó Feb 25 '22 at 15:51
  • @cmgchess Hidden next to the \`\`\` - I revealed it. – CherryDT Feb 25 '22 at 15:52
  • 4
    Don't use `Array.prototype.map` when you aren't doing something with a mapped array, use `Array.prototype.forEach` instead [JavaScript: Difference between .forEach() and .map()](https://stackoverflow.com/q/34426458/12101554) – Samathingamajig Feb 25 '22 at 15:53
  • 1
    You could demonstrate what you claim by making this a runnable snippet. Feel free to edit your question and make it a self-contained demonstration using the stack snippet editor. And by the way, that looks like it's computing the _total_ age, not the _average_ age. An _average_ calculation would divide the _total_ age by the _number_ of students. Is this really actual code? did you cut and paste it? or are you dividing by undefined somewhere else? (becase 1 / undefined is NaN) – Wyck Feb 25 '22 at 15:57
  • Can you debug the code and set a break point to look at the students array? One or more of your student objects are probably missing the age property. – Jeff LaFay Feb 25 '22 at 16:07
  • @Wyck sorry i was experimenting with the code and deleted the division part. forgot to add it when i posted the question but is constructing the array considered correct ? (in the second part) because i am supposed to create an array of students and ask the user to input the name and gender – aksak Feb 25 '22 at 16:35
  • `let students = [size]` This likely does not do what you intend. It creates an array with a single element in it like `[ 5 ]`. Then you proceed to push objects into it to get an array with one number at the beginning followed by a bunch of objects (students) like `[ 5, {name:'Alice'}, {name: 'Bob} ]` etc. Instead, just start with an empty array `students = []` – Wyck Feb 25 '22 at 16:39
  • @Wyck oh that makes sense, well this solved the problem thanks. im new to JS and i moved from java to this so i'm a little bit mixed up between about those things but thanks anw – aksak Feb 25 '22 at 16:44
  • I'll reiterate my advice from before. Next time you ask a question, I suggest trying to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) using the stack snippet editor. You never know what details might be relevant, but if a snippet reproduces your problem, then it's enough detail. This time, it turns out you forgot relevant code and mis-typed some of it. Using a live repro will help ensure that doesn't happen again and save us all time. – Wyck Feb 25 '22 at 16:54

2 Answers2

0

You can check 3 approaches down there for your problem:

const students = [
  { id: 1, name: "john", age: 25 },
  { id: 2, name: "jack", age: 31 },
  { id: 3, name: "joe", age: 26 },
  { id: 4, name: "jamal", age: 21 },
];

// Your approach:
function average_age() {
  let total = 0;
  let numberOfStudents = students.length;
  
  students.map(student => {
    total += Number(student.age);
  });
  
  return total / numberOfStudents;
}

// Second approach:
function average_age_second() {
  let total = 0;
  let numberOfStudents = students.length;
  
  students.forEach(student => {
    total += Number(student.age);
  });
  
  return total / numberOfStudents;
}

// Third approach: 
function average_age_third() {
  let numberOfStudents = students.length;
  
  const total = students.reduce((partialSum, student) => partialSum + student.age, 0);
  
  return total / numberOfStudents;
}   

console.log("Average age is : " + average_age());
console.log("Average age is : " + average_age_second());
console.log("Average age is : " + average_age_third());
Ben
  • 2,060
  • 9
  • 21
  • Sorry, our edits conflicted there. Go ahead. And please provide some context/explanation about the code or what you changed to the poster! – CherryDT Feb 25 '22 at 15:55
  • No problem, I completed the edit. I hope it is fine with you too. – Ben Feb 25 '22 at 15:56
0

Assuming the students array is in the format below (after you collected the inputs):

let students = [
  { name: "aaaa" , gender: "male"  , age: 17, grade: 63 },
  { name: "bbbb" , gender: "male"  , age: 20, grade: 70 },
  { name: "yyyy" , gender: "female", age: 18, grade: 45 },
  { name: "zzzz" , gender: "female", age: 18, grade: 70 },
  { name: "xxxx" , gender: "male"  , age: 20, grade: 83 },
];

One possible solution is the following:

let students = [
  { name: "aaaa" , gender: "male"  , age: 17, grade: 63 },
  { name: "bbbb" , gender: "male"  , age: 20, grade: 70 },
  { name: "yyyy" , gender: "female", age: 18, grade: 45 },
  { name: "zzzz" , gender: "female", age: 18, grade: 70 },
  { name: "xxxx" , gender: "male"  , age: 20, grade: 83 },
];
//------------------------------
function average_age(students){
let total = 0;
students.forEach(s => total +=s.age);
return total/students.length
}
//------------------------------
console.log("Average age is : " + average_age(students));
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42