Mapping an array to a new array with default values in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of start times and stop times for a stopwatch like this −

const arr = [
   { startTime: 1234, stopTime: 2345 },
   { startTime: 3452, stopTime: 9304 },
   { startTime: 2345, stopTime: 7432 },
   { startTime: 4567, stopTime: 6252 }
];

We are required to write a JavaScript function that takes one such array. Our function needs to turn them into one final array that is the actual amount of time that passed for each entry.

Therefore, for the above array, the output should look like −

const output = [ 1111, 5852, 5087, 1685 ];

Example

The code for this will be −

const arr = [
   { startTime: 1234, stopTime: 2345 },
   { startTime: 3452, stopTime: 9304 },
   { startTime: 2345, stopTime: 7432 },
   { startTime: 4567, stopTime: 6252 }
];
const findInterval = (arr = []) => {
   let res = [];
   res = arr.map(el => {
      const { startTime: sT, stopTime: eT } = el;
      const interval = eT - sT;
      return interval;
   });
   return res;
};
console.log(findInterval(arr));

Output

And the output in the console will be −

[ 1111, 5852, 5087, 1685 ]
raja
Published on 23-Nov-2020 09:52:36
Advertisements