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


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

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

更新于: 21-Nov-2020

505 次浏览

开启你的 职业生涯

通过完成课程取得认证

开始
广告