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
Here you go:
function convert(inputArray) {
var temp = {};
for(var i = 0; i < inputArray.length; i++) {
var subject = inputArray[i].subject;
// check if there is already an entry with this subject in the temp array
if(temp.hasOwnProperty(subject)) {
// if it is already in the list, add the marks and the noOfStudents
temp[subject].marks = temp[subject].marks + parseInt(inputArray[i].marks, 10);
temp[subject].noOfStudents = temp[subject].noOfStudents + parseInt(inputArray[i].noOfStudents, 10);
}
else {
// if it is not yet in the list, add a new object
temp[subject] = {
subject: subject,
marks: parseInt(inputArray[i].marks, 10),
noOfStudents: parseInt(inputArray[i].noOfStudents, 10)
}
}
}
// the temporary array is based on the subject, you are however interested on the effective value object
var result = [];
for(var entryKey in temp) {
result.push(temp[entryKey]);
}
return result;
}