javascriptarrayssumarrayobject

NaN after adding particular key element in an Array object


I have an Array object with 3000 objects. Among these 3000 few of them have grade and few object doesn't. Now I want to sum the grades. I'm getting NaN. Could you please guide me what am I doing wrong. Below is the sample code:

const arr=[
{
"name":"Harvey",
"grade":3
},
{
"name":"Pamela",
},
{
"name":"Scott",
"grade":4
},
{
"name":"Joshua",
"grade":5
},{
"name":"Rachel",
},{
"name":"Harvey",
"grade":3
},
]

let classTotal = arr.reduce(function (previousValue, currentValue) {
     return { 
       grade:  (previousValue.grade + currentValue.grade)
   }
   })
console.log(classTotal) //NaN

Also tried the following:

let classTotal=arr.reduce((accum, item) => accum + item.total, 0)
console.log(classTotal) // Same NaN

Solution

  • NaN is "Not a valid Number" you have some entries missing grade you should run filter to filter them out before your reduce

    const arr = [{
        "name": "Harvey",
        "grade": 3
      },
      {
        "name": "Pamela",
      },
      {
        "name": "Scott",
        "grade": 4
      },
      {
        "name": "Joshua",
        "grade": 5
      }, {
        "name": "Rachel",
      }, {
        "name": "Harvey",
        "grade": 3
      },
    ]
    
    let classTotal = arr.filter(function(element) {
      return element.grade
    }).reduce(function(previousValue, currentValue) {
      return {
        grade: (previousValue.grade + currentValue.grade)
      }
    })
    
    console.log(classTotal)

    Or, you can add a 0 for example for the elements who does not have a grade:

    const arr = [{
        "name": "Harvey",
        "grade": 3
      },
      {
        "name": "Pamela",
      },
      {
        "name": "Scott",
        "grade": 4
      },
      {
        "name": "Joshua",
        "grade": 5
      }, {
        "name": "Rachel",
      }, {
        "name": "Harvey",
        "grade": 3
      },
    ]
    
    let classTotal = arr.reduce(function(previousValue, currentValue) {
      return {
        grade: (previousValue.grade + (currentValue.grade || 0))
      }
    })
    
    console.log(classTotal)