Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to calculate total time between a list of entries?
Let's say, we have an array that contains some data about the speed of a motor boat during upstreams and downstreams like this ?
Following is our sample array ?
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
}];
console.log(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 }
]
We are required to write a function that takes in such type of array and finds the net velocity (i.e., velocity during upstream - velocity during downstream) of the boat during the whole course.
Using reduce() Method
So, let's write a function findNetVelocity(), iterate over the objects and calculate the net velocity. The full code for this function will be ?
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
Using for...of Loop
We can also solve this using a traditional for...of loop for better readability:
const findNetVelocityLoop = (arr) => {
let netVelocity = 0;
for (const entry of arr) {
if (entry.direction === 'upstream') {
netVelocity += entry.velocity;
} else {
netVelocity -= entry.velocity;
}
}
return netVelocity;
};
console.log(findNetVelocityLoop(arr));
67.5
How It Works
The calculation works as follows:
- Upstream velocities are added: 45 + 35 + 40 + 37.5 = 157.5
- Downstream velocities are subtracted: 15 + 50 + 25 = 90
- Net velocity = 157.5 - 90 = 67.5
Conclusion
Both approaches effectively calculate net velocity by adding upstream values and subtracting downstream values. The reduce() method provides a functional programming approach, while the for...of loop offers more explicit control flow.
