假设我们有一个对象数组,其中包含有关某些学生及其分数的数据,如下所示:
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' }, ];
我们需要编写一个包含一个这样的数组的JavaScript函数。
该功能应根据对象的“主题”属性消除冗余条目。此外,该功能应在单个对象中添加唯一对象的所有分数,而不添加学生数。
因此,对于上述数组,输出应类似于-
const output = [ { subject: 'Maths', marks: '70', noOfStudents: '17' }, { subject: 'Science', marks: '115', noOfStudents: '18' }, { subject: 'History', marks: '95', noOfStudents: '43' }, ];
为此的代码将是-
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));
输出结果
控制台中的输出将是-
[ { subject: 'Maths', marks: 30, noOfStudents: 12 }, { subject: 'Science', marks: 65, noOfStudents: 2 }, { subject: 'History', marks: 55, noOfStudents: 20 } ]