मान लीजिए, हमारे पास ऑब्जेक्ट्स का एक ऐरे है जिसमें एक टेस्ट में कुछ छात्रों के अंकों की जानकारी है:
const students = [
{ name: 'Andy', total: 40 },
{ name: 'Seric', total: 50 },
{ name: 'Stephen', total: 85 },
{ name: 'David', total: 30 },
{ name: 'Phil', total: 40 },
{ name: 'Eric', total: 82 },
{ name: 'Cameron', total: 30 },
{ name: 'Geoff', total: 30 }
];
हमें एक JavaScript फंक्शन लिखना है जो ऐसा एक ऐरे लेता है और उस छात्र का नाम और total वाला एक ऑब्जेक्ट रिटर्न करता है जिसका total के लिए सबसे अधिक मान है।
इसलिए, उपरोक्त ऐरे के लिए, आउटपुट होना चाहिए:
{ name: 'Stephen', total: 85 }
उदाहरण
निम्नलिखिक कोड है:
const students = [
{ name: 'Andy', total: 40 },
{ name: 'Seric', total: 50 },
{ name: 'Stephen', total: 85 },
{ name: 'David', total: 30 },
{ name: 'Phil', total: 40 },
{ name: 'Eric', total: 82 },
{ name: 'Cameron', total: 30 },
{ name: 'Geoff', total: 30 }
];
const pickHighest = arr => {
const res = {
name: '',
total: -Infinity
};
arr.forEach(el => {
const { name, total } = el;
if(total > res.total){
res.name = name;
res.total = total;
};
});
return res;
};
console.log(pickHighest(students));
आउटपुट
यह कंसोल पर निम्नलिखिक आउटपुट देगा:
{ name: 'Stephen', total: 85 }