일부 과목에서 일부 학생들이 채점한 점수를 포함하는 배열 배열이 있습니다. −
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
}
]
}
]