我有一组对象(学生),并且我正在尝试使用reduce函数查找最聪明的学生(成绩最高的学生)。这是我尝试过的,但无法获得正确的结果。
const students = [{
name: 'Chris',
score: 75
},
{
name: 'James',
score: 54
},
{
name: 'Alex',
score: 32
},
{
name: 'Mary',
score: 43
},
{
name: 'Robert',
score: 87
}
];
const initValue = {
name: '',
maxScore: 0
};
function smartStudentReducer(acc, student) {
return {
name: student.name,
score: Math.max(acc.maxScore, student.score)
}
}
const smartStudent = students.reduce(smartStudentReducer, initValue);
console.log(smartStudent);
答案 0 :(得分:2)
只有name:
高于student.name
时,reducer函数才应将student.score
属性设置为acc.maxStore
。因此,您需要使用条件条件。
此外,累加器需要返回一个具有与initValue
相同属性的对象。我将initValue
更改为与students
对象类似,因此当分数更高时,我可以简单地返回student
。
const initValue = {
name: '',
score: 0
};
function smartStudentReducer(acc, student) {
return student.score > acc.score ? student : acc;
}
const students = [{
name: 'Chris',
score: 75
},
{
name: 'James',
score: 54
},
{
name: 'Alex',
score: 32
},
{
name: 'Mary',
score: 43
},
{
name: 'Robert',
score: 87
}
];
const smartStudent = students.reduce(smartStudentReducer, initValue);
console.log(smartStudent);
答案 1 :(得分:0)
实际上,每个reduce
的周期都将覆盖结果。哪个学生得分最高并不重要,结果始终是数据数组的最后一个学生。
其次,您缺少一些简单的条件来检查当前循环播放的学生的分数是否高于先前的分数。
建议的方法:
const students = [{
name: 'Chris',
score: 75
},
{
name: 'James',
score: 54
},
{
name: 'Alex',
score: 32
},
{
name: 'Mary',
score: 43
},
{
name: 'Robert',
score: 87
}
];
const initValue = {};
function smartStudentReducer(acc, student) {
if (!acc.name) {
acc = student;
} else {
if (acc.score < student.score) {
acc = student;
}
}
return acc;
}
const smartStudent = students.reduce(smartStudentReducer, initValue);
console.log(smartStudent);