我需要提供一种解决方案,以显示班上学生的最高分数。
function highestScore (students) {
//代码在这里 }
// TEST CASE
console.log(highestScore([
{
name: 'Daisy',
score: 90,
class: 'foxes'
},
{
name: 'Alexander',
score: 85,
class: 'wolves'
},
{
name: 'Sergio',
score: 74,
class: 'foxes'
},
{
name: 'Anabelle',
score: 78,
class: 'wolves'
}
]));
From the parameter, the function would return the name of each class and
display the highest student's name and score of that student.
function highestScore (students) {
var classes = {};
var scores = [];
for(i=0; i<students.length; i++){
var inputClass = students[i].class;
var inputScore = students[i].score;
var inputName = students[i].name;
var classScore = [];
var isExist = false;
var object = Object.values(class);
return classScore;
}
// TEST CASE
console.log(highestScore([
{
name: 'Daisy',
score: 90,
class: 'foxes'
},
{
name: 'Alexander',
score: 85,
class: 'wolves'
},
{
name: 'Sergio',
score: 74,
class: 'foxes'
},
{
name: 'Anabelle',
score: 78,
class: 'wolves'
}
]));
The result would show something like this.
// {
// foxes: { name: 'Daisy', score: 90 },
// wolves: { name: 'Alexander', score: 85 }
// }
答案 0 :(得分:0)
您可以reduce
进入一个对象,该对象的键是班级名称,其值是该班级当前的最高学生。在每次迭代中,如果该班级还不存在任何值,则分配学生-否则,仅当该班级的学生得分较低时,才分配该学生:
function highestScore(arr) {
const highestByClass = arr.reduce((a, student) => {
const { class: className, score } = student;
if (!a[className] || a[className].score < score) {
a[className] = student;
}
return a;
}, {});
return Object.values(highestByClass);
}
console.log(highestScore([
{
name: 'Daisy',
score: 90,
class: 'foxes'
},
{
name: 'Alexander',
score: 85,
class: 'wolves'
},
{
name: 'Sergio',
score: 74,
class: 'foxes'
},
{
name: 'Anabelle',
score: 78,
class: 'wolves'
}
]));
答案 1 :(得分:0)
我当前的解决方法如下。
function highestScore (students) {
var object = {};
var result = [];
for (var i=0; i<students.length; i++){
var nameInput = students[i].name
var scoreInput = students[i].score
var classInput = students[i].class
if(object[classInput] === undefined){
object[classInput] = {
name: nameInput,
score: scoreInput,
}
}
for(var j=0; j<students.length; j++){
if(students[j].class === object[students[i].class] && students[j].score > object[students[i].class].score){
object[classInput] = {
name: students[j].name,
score: students[j].score,
}
}
}
}
return object;
}
但是,如果要追赶的学生的分数高于最初的分数,我将无法插入新值。
// TEST CASE
console.log(highestScore([
{
name: 'Dimitri',
score: 90,
class: 'foxes'
},
{
name: 'Alexei',
score: 85,
class: 'wolves'
},
{
name: 'Sergei',
score: 94,
class: 'foxes'
},
{
name: 'Anastasia',
score: 78,
class: 'wolves'
}
]));