【问题标题】:Languages Statistic语言统计
【发布时间】:2022-01-04 09:16:00
【问题描述】:

我必须实现“getLanguagesStatistic”功能,这将有助于 IT 杂志总结 2019 年编程语言的流行度。

作为输入,该函数接收一组用户评论。您需要以{languageName: count, anotherLanguageName: anotherCount, ...} 格式返回一个对象,其中languageName 是字符串中language 的名称,count 是使用这种语言的程序员留下的评论数。

在这种情况下,仅应考虑 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)
    
};

【问题讨论】:

    标签: javascript arrays object


    【解决方案1】:

    类似的东西

    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);

    【讨论】:

      猜你喜欢
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 2011-06-27
      • 2021-05-28
      • 2011-01-13
      • 2019-10-31
      • 1970-01-01
      相关资源
      最近更新 更多