I have an array of objects where i need sum of object property values in new array of objects,
Input:
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' },
.
.
.
];
Output i need,
var outputArray = [
{ subject: 'Maths', marks: '70', noOfStudents: '17' },
{ subject: 'Science', marks: '115', noOfStudents: '18' },
{ subject: 'History', marks: '95', noOfStudents: '43' },
.
.
.
];
I want sum of marks and no of students of subjects in new object array. There would be N number of other subject objects (i.e-Geography, Physics etc) in the input array.
The solution using
Array.forEach
,parseInt
andObject.keys
functions:The output:
Here you go:
Just another proposal with an object as hashtable.
You can do this with
forEach
andthisArg
optional parameterYou can use
forEach()
to iterate and generate the new arrayUsing
reduce()
methodFYI : You can avoid the
key
object by usingfind()
method, but performance wise that may be little bit slower.