मान लीजिए, हमारे पास वस्तुओं की एक सरणी है जिसमें एक परीक्षा में कुछ छात्रों के अंकों के बारे में जानकारी है -
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 }
]; हमें एक जावास्क्रिप्ट फ़ंक्शन लिखने की आवश्यकता होती है जो एक ऐसी सरणी लेता है और उस छात्र के नाम और कुल के साथ एक ऑब्जेक्ट देता है जिसका कुल मूल्य उच्चतम होता है।
इसलिए, उपरोक्त सरणी के लिए, आउटपुट होना चाहिए -
{ 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 }