สมมติว่าเรามีอาร์เรย์ที่มีข้อมูลบางอย่างเกี่ยวกับความเร็วของเรือยนต์ระหว่างต้นน้ำและปลายน้ำเช่นนี้ −
ต่อไปนี้เป็นอาร์เรย์ตัวอย่างของเรา -
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