Home > Net >  Finding the average time between an array of timestamps in javascript
Finding the average time between an array of timestamps in javascript

Time:08-03

I'm trying to get the average time between these timestamps. But it keeps coming out as

"average = ", "Wed Dec 31 1969 20:48:03 GMT-0800 (Pacific Standard Time)"

How can I get the correct average between the dates below ? Here is my code below.

const timeStamps = [
  "Tue Aug 02 2022 09:47:39 GMT-0700 (PST)",
  "Mon Aug 01 2022 09:47:39 GMT-0700 (PST)",
  "Tue Aug 02 2022 09:47:42 GMT-0700 (PST)",
  "Tue Aug 02 2022 09:47:02 GMT-0700 (PST)",
  "Tue Aug 02 2022 09:47:55 GMT-0700 (PST)",
];

const sortedDates = timeStamps.map((t) => new Date(t)).sort((a, b) => a - b);
const average =
  (sortedDates[sortedDates.length - 1] - sortedDates[0]) / sortedDates.length -
  1;
  
console.log("average = ", new Date(average).toString());

CodePudding user response:

The arithmetic mean or the average is the sum of all the numbers divided by the count of numbers in any collection.

We could sum up all the timestamps and divide it with the array length.

Note that the items in the timestamps array are strings, we could get their UNIX timestamp with new Date(timestamp).valueOf().

const timestamps = [
  "Tue Aug 02 2022 09:47:39 GMT-0700 (PST)",
  "Mon Aug 01 2022 09:47:39 GMT-0700 (PST)",
  "Tue Aug 02 2022 09:47:42 GMT-0700 (PST)",
  "Tue Aug 02 2022 09:47:02 GMT-0700 (PST)",
  "Tue Aug 02 2022 09:47:55 GMT-0700 (PST)",
];

let sum = 0;

for (let i = 0; i < timestamps.length; i  ) {
    sum  = new Date(timestamps[i]).valueOf();
}

const average = sum / timestamps.length;
console.log(average); // or console.log(new Date(average));

CodePudding user response:

Try this:

const timeStamps = ['Tue Aug 02 2022 09:47:39 GMT-0700 (PST)', 'Mon Aug 01 2022 09:47:39 GMT-0700 (PST)', 'Tue Aug 02 2022 09:47:42 GMT-0700 (PST)',  'Tue Aug 02 2022 09:47:02 GMT-0700 (PST)', 'Tue Aug 02 2022 09:47:55 GMT-0700 (PST)' ]

const ts = timeStamps.map(time => new Date(time).getTime());

const average = ts.reduce((acc, val) => acc   val) / timeStamps.length;

console.log("average = ", new Date(average));

CodePudding user response:

Why is it this formula??? const average = (sortedDates[sortedDates.length - 1] - sortedDates[0]) / sortedDates.length - 1;

  • Related