ধরা যাক, আমাদের কাছে অবজেক্টের একটি অ্যারে রয়েছে যাতে কিছু ছাত্রের পরীক্ষার মার্কসের তথ্য আছে:
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 }
];
আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এমন একটি অ্যারে নেয় এবং সবচেয়ে বেশি 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 }