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

前端 未结 5 978
时光取名叫无心
时光取名叫无心 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:26

    Just another proposal with an object as hashtable.

    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 (a) {
        if (!this[a.subject]) {
            this[a.subject] = { subject: 'Maths', marks: '0', noOfStudents: '0' };
            outputArray.push(this[a.subject]);
        }
        this[a.subject].marks = (+this[a.subject].marks + +a.marks).toString();
        this[a.subject].noOfStudents = (+this[a.subject].noOfStudents + +a.noOfStudents).toString();
    }, Object.create(null));
    
    console.log(outputArray);

提交回复
热议问题