JavaScript 用获取分数最高的数组项
我们有一个数组,其中包含一些学生在某些科目中获得的分数
const arr = [ ['Math', 'John', 100], ['Math', 'Jake', 89], ['Math', 'Amy', 93], ['Science', 'Jake', 89], ['Science', 'John', 89], ['Science', 'Amy', 83], ['English', 'John', 82], ['English', 'Amy', 81], ['English', 'Jake', 72] ];
我们需要编写一个函数,该函数接受此数组并返回一个对象数组,其中每个对象对应一门科目,并包含该科目中最高得分者的详细信息。
我们的输出应如下所示
[
{ "Subject": "Math",
"Top": [
{ Name: "John", Score: 100}
]
},
{ "Subject": "Science",
"Top": [
{ Name: "Jake", Score: 89},
{ Name: "John", Score: 89}
]
},
{ "Subject": "English",
"Top": [
{ Name: "John", Score: 82}
]
}
]我们编写此函数的代码如下
示例
const arr = [
['Math', 'John', 100],
['Math', 'Jake', 89],
['Math', 'Amy', 93],
['Science', 'Jake', 89],
['Science', 'John', 89],
['Science', 'Amy', 83],
['English', 'John', 82],
['English', 'Amy', 81],
['English', 'Jake', 72]
];
const groupScore = arr => {
return arr.reduce((acc, val, index, array) => {
const [sub, name, score] = val;
const ind = acc.findIndex(el => el['Subject'] === val[0]);
if(ind !== -1){
if(score > acc[ind]["Top"][0]["score"]){
acc[ind]["Top"] = [{
"name": name,"score": score
}];
}else if(score === acc[ind]["Top"][0]["score"]){
acc[ind]["Top"].push({
"name": name,"score": score
});
}
}else{
acc.push({
"Subject": sub,"Top": [{"name": name, "score": score}]
});
};
return acc;
}, []);
};
console.log(JSON.stringify(groupScore(arr), undefined, 4));输出
控制台中的输出如下
const arr = [
['Math', 'John', 100],
['Math', 'Jake', 89],
['Math', 'Amy', 93],
['Science', 'Jake', 89],
['Science', 'John', 89],
['Science', 'Amy', 83],
['English', 'John', 82],
['English', 'Amy', 81],
['English', 'Jake', 72]
];
const groupScore = arr => {
return arr.reduce((acc, val, index, array) => {
const [sub, name, score] = val;
const ind = acc.findIndex(el => el['Subject'] === val[0]);
if(ind !== -1){
if(score > acc[ind]["Top"][0]["score"]){
acc[ind]["Top"] = [{
"name": name,"score": score
}];
}else if(score === acc[ind]["Top"][0]["score"]){
acc[ind]["Top"].push({
"name": name,"score": score
});
}
}else{
acc.push({
"Subject": sub,"Top": [{"name": name, "score": score}]
});
};
return acc;
}, []);
};
console.log(JSON.stringify(groupScore(arr), undefined, 4));[
{
"Subject": "Math",
"Top": [
{
"name": "John","score": 100
}
]
},
{
"Subject": "Science",
"Top": [
{
"name": "Jake",
"score": 89
},
{
"name": "John",
"score": 89
}
]
},
{
"Subject": "English",
"Top": [
{
"name": "John",
"score": 82
}
]
}
]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP