JavaScript 中新对象数组中数组对象属性值的总和

javascriptweb developmentfront end technologyobject oriented programming

假设我们有一个对象数组,其中包含一些学生及其分数的数据,如下所示 −

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 函数来接收一个这样的数组。

该函数应根据对象的"subject"属性消除冗余条目。此外,该函数应将所有分数和学生人数添加到该单个对象中的唯一对象中。

因此,对于上述数组,输出应如下所示 −

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 }
]

相关文章