Sum of array object property values in new array of objects in Javascript

前端 未结 5 964
时光取名叫无心
时光取名叫无心 2020-11-27 23:41

I have an array of objects where i need sum of object property values in new array of objects,

Input:

var inputArray = [
  { subject: \'Maths\', mark         


        
5条回答
  •  春和景丽
    2020-11-28 00:30

    You can do this with forEach and thisArg optional parameter

    var inputArray = [
      { subject: 'Maths', marks: '40', noOfStudents: '5' },
      { subject: 'Science', marks: '50', noOfStudents: '16' },
      { subject: 'History', marks: '35', noOfStudents: '23' },
      { subject: 'Science', marks: '65', noOfStudents: '2' },
      { subject: 'Maths', marks: '30', noOfStudents: '12' },
      { subject: 'History', marks: '55', noOfStudents: '20' },
    ], outputArray = [];
      
    inputArray.forEach(function(e) {
      if(!this[e.subject]) {
        this[e.subject] = { subject: e.subject, marks:  0, noOfStudents: 0 }
         outputArray.push(this[e.subject]);
       }
      this[e.subject].marks += Number(e.marks);
      this[e.subject].noOfStudents += Number(e.noOfStudents);
    }, {});
    
    console.log(outputArray)

提交回复
热议问题