Cho mảng dữ liệu tốc độ tàu lên/xuống dòng:
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 }]Viết hàm findNetVelocity() tính vận tốc ròng (upstream - downstream).
Ví dụ
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));Kết quả
Đầu ra console:
67.5