如何使用函数式编程重构JavaScript代码

时间:2019-04-26 20:31:40

标签: javascript functional-programming

我试图通过一本教科书学习使用JavaScript进行函数式编程。我必须使用函数式编程及其困难来重构一些代码。如何使用map()filter()reduce()重新编写此代码。

我必须以更实用的方式重新编写以下代码。我已经尝试过了,但是我不断得到空数组。

const students = [{
    name: "Anna",
    sex: "f",
    grades: [4.5, 3.5, 4]
  },
  {
    name: "Dennis",
    sex: "m",
    country: "Germany",
    grades: [5, 1.5, 4]
  },
  {
    name: "Martha",
    sex: "f",
    grades: [5, 4, 2.5, 3]
  },
  {
    name: "Brock",
    sex: "m",
    grades: [4, 3, 2]
  }
];

// Compute female student results
const femaleStudentsResults = [];
for (const student of students) {
  if (student.sex === "f") {
    let gradesSum = 0;
    for (const grade of student.grades) {
      gradesSum += grade;
    }
    const averageGrade = gradesSum / student.grades.length;
    femaleStudentsResults.push({
      name: student.name,
      avgGrade: averageGrade
    });
  }
}

console.log(femaleStudentsResults);

结果必须与此相同:

[Object{avgGrade: 4, name: 'Anna'}, Object{avgGrade: 3.625, name: 'Martha'}]

我首先以

分隔所有女学生

const females = students.filter(gender => gender.sex === 'f')

然后,返回我所做成绩的数组

const grade = females.map(grade => grade.grades);

但是当我尝试使用reduce()来查找平均成绩时:

 const grade = females
   .map(grade => grade.grades)
   .reduce((accum,curr)=>accum + curr)

我得到以下结果4.5,3.5,45,4,2.5,3。如何防止这种情况,只获得每个学生的平均成绩的平均值?

1 个答案:

答案 0 :(得分:3)

使用var vm = new Vue({ el: '#l-main', data: { variations: { '41783' : { 'name': 'test1', 'primary': false }, '41785' : { 'name': 'test2', 'primary': true } } }, methods: { onChange($event) { // the primary variation is the one whose key // matches the value of the radio button that got checked for (const key in this.variations) { this.variations[key].primary = key === $event.target.value; } } } }); (吸引女学生),然后使用filter(将学生对象转换为带有.map的对象),代替:

avgGrade