does anyone know how to compute inside grades? i tried use function but not working and i also try const grades = ‘grades’; but still not computing inside grades anyone know the algo of this?
const students = [{
name: 'Khelly',
grades: [78, 92, 85, 88]
},
{
name: 'Jared',
grades: [90, 86, 94, 89]
},
{
name: 'Alio',
grades: [72, 84, 80, 76]
},
{
name: 'Alvin',
grades: [68, 72, 65, 80]
}];
const grades = 'grades';
function calculateCar(array, property) {
const total = array.reduce((accumulator, object) => {
return accumulator + object[grades];
}, 0)
return total;
}
const totalCar = calculateCar(students, 'price');
console.log(calculateCar);
2
Answers
You need to use
Array.reduce()
forobject[grades]
in order to get total valueBTW:
property
is useless in your code snippet,it’s a better way to pass property value viacalculateCar
parameters.The OP mentioned the desired result as
[ { name: 'Khelly', grades:95}, { name: 'Jared', grades: 87}, { name: 'Alio', grades: 83}, { name: 'Alvin', grades:82} ]
. So just map the array and calculate sum of grades for each student: