हमारे पास सरणियों की एक सरणी है जिसमें कुछ छात्रों द्वारा कुछ विषयों में प्राप्त अंक शामिल हैं -
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
}
]
}
]