按 JavaScript 数组对象分组

javascriptweb developmentfront end technologyobject oriented programming

假设我们有一个数组数组,其中包含一些学生在某些科目的成绩,例如 −

const arr = [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ];

我们需要编写一个 JavaScript 函数,该函数接受一个这样的数组并返回一个对象对象。

返回对象应包含每个唯一主题的对象,并且该对象应包含该语言出现的次数、总分总和和平均分等信息。

示例

其代码为 −

const arr = [
   ["English", 52],
   ["Hindi", 154],
   ["Hindi", 241],
   ["Spanish", 10],
   ["French", 65],
   ["German", 98],
   ["Russian", 10]
];
const groupSubjects = arr => {
   const grouped = arr.reduce((acc, val) => {
      const [key, total] = val;
      if(!acc.hasOwnProperty(key)){
         acc[key] = {
            'count': 0,
            'total': 0
         };
      };
      const accuKey = acc[key];
      accuKey['count']++;
      accuKey['total'] += total;
      accuKey['average'] = total / accuKey['count'];
      return acc;
   }, {});
   return grouped;
};
console.log(groupSubjects(arr));

输出

控制台中的输出将是 −

{
English: { count: 1, total: 52, average: 52 },
Hindi: { count: 2, total: 395, average: 120.5 },
Spanish: { count: 1, total: 10, average: 10 },
French: { count: 1, total: 65, average: 65 },
German: { count: 1, total: 98, average: 98 },
Russian: { count: 1, total: 10, average: 10 }
}

相关文章