按 JavaScript 陣列物件分組
假設我們有一個包含一些學生在一些學科中的分數的陣列,如下所示 -
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 }
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP