Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm thế nào để tính toán tổng thời gian giữa một danh sách các mục nhập?

Giả sử, chúng ta có một mảng chứa một số dữ liệu về tốc độ của thuyền máy khi ngược dòng và xuôi dòng như thế này -

Sau đây là mảng mẫu của chúng tôi -

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
}]

Chúng tôi được yêu cầu viết một hàm nhận dạng mảng như vậy và tìm vận tốc thực (tức là vận tốc khi ngược dòng - vận tốc khi xuôi dòng) của thuyền trong suốt quá trình.

Vì vậy, hãy viết một hàm findNetVelocity (), lặp qua các đối tượng và tính vận tốc thực. Mã đầy đủ cho hàm này sẽ là -

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));

Đầu ra

Đầu ra trong bảng điều khiển sẽ là -

67.5