得分最高的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
}
]
}
]