Skip to content
Advertisement

Is there a cleaner way to calculate user session length from such an array?

I have an array of events where every event has an action (login/logout) and a timestamp.

JavaScript

I am trying to write a function calculating the total user session length which is defined by the difference between a login and logout. And a login always comes before a logout.

JavaScript

This works but I wonder if there is a simpler or cleaner way to calculate it? Right now I need to use an extra variable to keep track of the last login timestamp while traversing the array.

Advertisement

Answer

If login events are always followed by logout events, you can simply subtract the sum of the login timestamps from the sum of the logout timestamps:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement