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
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);