我必須實作“getLanguagesStatistic”功能,這將有助于IT雜志從編程語言的流行度方面總結2019年。
作為輸入,該函式接收一組用戶評論。你需要的格式回傳一個物件{languageName: count, anotherLanguageName: anotherCount, ...},其中languageName是名語言字串中,并計數是通過使用這種語言的程式員留下評語數量。
在這種情況下,只應考慮 2019 年留下的那些用戶評論。撤銷年份存盤在year欄位中,語言存盤在language欄位中。
反饋按以下格式提供:
{ firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C', year: 2019 }
輸入資料:
const data = [
{ firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C', year: 2019 },
{ firstName: 'Anna', lastName: 'R.', country: 'Liechtenstein', continent: 'Europe', age: 52, language: 'JavaScript', year: 2019 },
{ firstName: 'Piter', lastName: 'G.', country: 'Sweden', continent: 'Europe', age: 30, language: 'JavaScript', year: 2019 },
{ firstName: 'Ramon', lastName: 'R.', country: 'Paraguay', continent: 'Americas', age: 29, language: 'Ruby', year: 2014 },
{ firstName: 'George', lastName: 'B.', country: 'England', continent: 'Europe', age: 81, language: 'C', year: 2016 },
];
const result = getLanguagesStatistic(data);
輸出資料:
console.log(result);
// {
// C: 1,
// JavaScript: 2
// }
功能:
const getLanguagesStatistic = (feedbacks) => {
//code here
};
我剛剛設法制作了年度最佳過濾器。我通過reduce,destructuring嘗試了其余的功能,但它不起作用,所以我只寫了我所做的。
我真的需要在這里使用解構嗎?
我的嘗試:
const getLanguagesStatistic = (feedbacks) => {
return feedbacks.filter( (f) => f.year == 2019)
};
uj5u.com熱心網友回復:
像這樣的東西
const getLanguagesStatistic = (feedbacks) => {
return feedbacks.reduce((acc, {language, year}) => {
if (year === 2019) {
acc[language] = (acc[language]||0) 1;
}
return acc;
}, {});
};
const data = [
{ firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C', year: 2019 },
{ firstName: 'Anna', lastName: 'R.', country: 'Liechtenstein', continent: 'Europe', age: 52, language: 'JavaScript', year: 2019 },
{ firstName: 'Piter', lastName: 'G.', country: 'Sweden', continent: 'Europe', age: 30, language: 'JavaScript', year: 2019 },
{ firstName: 'Ramon', lastName: 'R.', country: 'Paraguay', continent: 'Americas', age: 29, language: 'Ruby', year: 2014 },
{ firstName: 'George', lastName: 'B.', country: 'England', continent: 'Europe', age: 81, language: 'C', year: 2016 },
];
const result = getLanguagesStatistic(data);
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366738.html
標籤:javascript 数组 目的
