เรามีอาร์เรย์ของอาร์เรย์ที่มีคะแนนโดยนักเรียนบางคนในบางวิชา -
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
}
]
}
]