ধরা যাক, আমাদের কাছে একটি অ্যারে রয়েছে যাতে একটি মোটর বোটের গতি সম্পর্কে কিছু ডেটা রয়েছে আপস্ট্রিম এবং ডাউনস্ট্রিমের সময় এইরকম -
নিম্নলিখিত আমাদের নমুনা অ্যারে -
const arr = [{
direction: 'upstream',
velocity: 45
}, {
direction: 'downstream',
velocity: 15
}, {
direction: 'downstream',
velocity: 50
}, {
direction: 'upstream',
velocity: 35
}, {
direction: 'downstream',
velocity: 25
}, {
direction: 'upstream',
velocity: 40
}, {
direction: 'upstream',
velocity: 37.5
}] আমাদের এমন একটি ফাংশন লিখতে হবে যা এই ধরনের অ্যারে নেয় এবং পুরো পথ চলাকালীন নৌকার নেট বেগ (অর্থাৎ আপস্ট্রিমের সময় বেগ - ডাউনস্ট্রিমের সময় বেগ) খুঁজে পায়।
সুতরাং, আসুন একটি ফাংশন লিখি findNetVelocity(), বস্তুর উপর পুনরাবৃত্তি করি এবং নেট বেগ গণনা করি। এই ফাংশনের জন্য সম্পূর্ণ কোড হবে −
উদাহরণ
const arr = [{
direction: 'upstream',
velocity: 45
}, {
direction: 'downstream',
velocity: 15
}, {
direction: 'downstream',
velocity: 50
}, {
direction: 'upstream',
velocity: 35
}, {
direction: 'downstream',
velocity: 25
}, {
direction: 'upstream',
velocity: 40
}, {
direction: 'upstream',
velocity: 37.5
}];
const findNetVelocity = (arr) => {
const netVelocity = arr.reduce((acc, val) => {
const { direction, velocity } = val;
if(direction === 'upstream'){
return acc + velocity;
}else{
return acc - velocity;
};
}, 0);
return netVelocity;
};
console.log(findNetVelocity(arr)); আউটপুট
কনসোলে আউটপুট হবে −
67.5