![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }]
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.
So, let’s write a function findNetVelocity(), iterate over the objects and calculate the net velocity. The full code for this function will be −
Example
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));
Output
The output in the console will be −
67.5
Advertisements