1

I'm new to JavaScript and I tried so many things already. I have to sum all values (grades) for each person inside the function. So when I call the function outside with

console.log(totalNumberOfGrades(// I have to put here any of the three person objects... ));

so the inside of the function can sum the values. I tried it with .reduce and for...in loops but I can't figure out how to access the values of the objects property when I use the array allPerson. Thanks for your help and I continue learning.

var person1 = {
    gradeMath: 2,
    gradeBio: 3,
    gradeEnglish: 1
};

var person2 = {
    gradeMath: 1,
    gradeBio: 2,
    gradeEnglish: 2
};

var person3 = {
    gradeMath: 3,
    gradeBio: 4,
    gradeEnglish: 3
};

var allPerson = [person1, person2, person3];

function totalNumberOfGrades(person) {
    // return the sum of grades for each person

}

The result look like this:

console.log(totalNumberOfGrades(person1); = 6
THess
  • 1,003
  • 1
  • 13
  • 21
  • 1
    Welcome to SO. This looks like homework. Please show us what you've tried. Ans remember, StackOverflow isn't meant to do the work for you, but to help you debug. – Alexandre Elshobokshy Mar 10 '20 at 09:46
  • How is `allPerson` relevant here, i.e. how/where is it supposed to be used? Do you know how to access properties in general? Maybe this helps: [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383/218196) – Felix Kling Mar 10 '20 at 09:46
  • Does this answer your question? [How to sum the values of a JavaScript object?](https://stackoverflow.com/questions/16449295/how-to-sum-the-values-of-a-javascript-object) – AZ_ Mar 10 '20 at 09:51

3 Answers3

1

You can use Object.values and Array.reduce prototype.

function totalNumberOfGrades(person) { // return the sum of grades for each person
  return Object.values(person) // return array: [2, 3, 1] with person1
               .reduce((total, grade) => total + grade, 0)
}
Alexandre Nicolas
  • 1,851
  • 17
  • 19
0

I assume you want to sum every grade in each object

var person1 = {
  gradeMath: 2,
  gradeBio: 3,
  gradeEnglish: 1
};

var person2 = {
  gradeMath: 1,
  gradeBio: 2,
  gradeEnglish: 2
};

var person3 = {
  gradeMath: 3,
  gradeBio: 4,
  gradeEnglish: 3
};

var allPerson = [person1, person2, person3];

const result = allPerson.reduce((acc, x) => {
  const sumAllGrades = Object.values(x).reduce((acc, y) => acc + y, 0);
  return acc + sumAllGrades;
}, 0)
console.log(result)
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
0

Use forEach on Object.values

var person1 = {
    gradeMath: 2,
    gradeBio: 3,
    gradeEnglish: 1
};

function totalNumberOfGrades(person) {
  let sum = 0;
  Object.values(person).forEach(val => (sum += val));
  return sum;
}

console.log(totalNumberOfGrades(person1));
Siva K V
  • 10,561
  • 2
  • 16
  • 29