假设我们有一个数组数组,其中包含某些学科的某些学生的分数,如下所示:
const arr = [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组并返回一个object对象。
返回对象应为每个唯一主题包含一个对象,并且该对象应包含该语言的出现次数,总分和平均值之类的信息。
为此的代码将是-
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 } }