Reputation: 13
here's the object with arrays:
const studentGrades = [
[{ studentID: 1, Q1: 89.3, Q2: 91.2, Q3: 93.3, Q4: 89.8 }],
[{ studentID: 2, Q1: 69.2, Q2: 71.3, Q3: 76.5, Q4: 81.9 }],
[{ studentID: 3, Q1: 95.7, Q2: 91.4, Q3: 90.7, Q4: 85.6 }],
[{ studentID: 4, Q1: 86.9, Q2: 74.5, Q3: 83.3, Q4: 86.1 }],
[{ studentID: 5, Q1: 70.9, Q2: 73.8, Q3: 80.2, Q4: 81.8 }]
];
I tried doing the following, it must have 1 decimal point and must be a number:
studentGrades.forEach( function(grade){
grade.average = grade.Q1 + grade.Q2 + grade.Q3 + grade.Q4/4
parseFloat(grade.average).toFixed(1);
});
But it keeps returning NaN in my console.
Upvotes: 1
Views: 44
Reputation: 314
You must add [0] to grade because your studentGrades is a array of arrays.
studentGrades.forEach( function(grade){
grade.average = (grade[0].Q1 + grade[0].Q2 + grade[0].Q3 + grade[0].Q4) / 4;
parseFloat(grade.average).toFixed(1);
});
Upvotes: 1
Reputation: 3910
Your data is Array inside an array, hence you need to add grade[0]
const studentGrades = [
[{ studentID: 1, Q1: 89.3, Q2: 91.2, Q3: 93.3, Q4: 89.8 }],
[{ studentID: 2, Q1: 69.2, Q2: 71.3, Q3: 76.5, Q4: 81.9 }],
[{ studentID: 3, Q1: 95.7, Q2: 91.4, Q3: 90.7, Q4: 85.6 }],
[{ studentID: 4, Q1: 86.9, Q2: 74.5, Q3: 83.3, Q4: 86.1 }],
[{ studentID: 5, Q1: 70.9, Q2: 73.8, Q3: 80.2, Q4: 81.8 }]
];
studentGrades.forEach( function(grade){
grade[0].average = (grade[0].Q1 + grade[0].Q2 + grade[0].Q3 + grade[0].Q4)/4;
parseFloat(grade[0].average).toFixed(1);
});
console.log(studentGrades);
Upvotes: 1
Reputation: 895
studentGrades is an array of arrays, you should remove the brackets outside the actual studentGrade if they are not necessary and make it like this :
const studentGrades = [
{ studentID: 1, Q1: 89.3, Q2: 91.2, Q3: 93.3, Q4: 89.8 },
{ studentID: 2, Q1: 69.2, Q2: 71.3, Q3: 76.5, Q4: 81.9 },
{ studentID: 3, Q1: 95.7, Q2: 91.4, Q3: 90.7, Q4: 85.6 },
{ studentID: 4, Q1: 86.9, Q2: 74.5, Q3: 83.3, Q4: 86.1 },
{ studentID: 5, Q1: 70.9, Q2: 73.8, Q3: 80.2, Q4: 81.8 }
];
Upvotes: 1