Suppose we have an array of objects that contains the data about some students and their marks like this −
const arr = [ { 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' }, ];
We are required to write a JavaScript function that takes in one such array.
The function should eliminate the redundant entries on the basis of the 'subject' property of objects. Moreover, the function should add all the marks and no of students for a unique object in that single object.
Therefore, for the above array, the output should look like −
const output = [ { subject: 'Maths', marks: '70', noOfStudents: '17' }, { subject: 'Science', marks: '115', noOfStudents: '18' }, { subject: 'History', marks: '95', noOfStudents: '43' }, ];
Example
The code for this will be −
const arr = [ { 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' }, ]; const groupBySubject = (arr = []) => { const map = {}; let res = []; res = arr.reduce((acc, val) => { const { subject, marks, noOfStudents } = val; const { length: l } = acc; if(map.hasOwnProperty(subject)){ acc[map[subject]]['marks'] = +marks; acc[map[subject]]['noOfStudents'] = +noOfStudents; } else{ map[subject] = l; acc.push({ subject: subject, marks: +marks, noOfStudents: +noOfStudents }); }; return acc; }, []); return res; }; console.log(groupBySubject(arr));
Output
And the output in the console will be −
[ { subject: 'Maths', marks: 30, noOfStudents: 12 }, { subject: 'Science', marks: 65, noOfStudents: 2 }, { subject: 'History', marks: 55, noOfStudents: 20 } ]