Home > Back-end >  How to calculate the number of occurrences and assign them to the appropriate place?
How to calculate the number of occurrences and assign them to the appropriate place?

Time:05-31

I've got an array of times in epoch like below:

const times = [1653931370, 1653924170, 1653920570, 1653913370, 1653913370, 1653902570]

all of this dates is from one single day between 00:00 and 23:59. Right now i need to assign each of these times to a specific hour along with the number of occurrences of that hour. My response should be like below:

[
    {
        hour: 0, //00:00
        occurs: 4
    },
    {
        hour: 1, //01:00
        occurs: 4
    },

    ...

    {
        hour: 22, //22:00
        occurs: 17
    },
    {
        hour: 23, //23:00
        occurs: 12
    },
]

can someone help me with this issue? Thanks for any help!

CodePudding user response:

  1. Map over the array and get the hours using the Date.prototype.getHours method.

  2. Then group the hours using Array.prototype.reduce.

const times = [
  1653931370, 1653924170, 1653920570, 1653913370, 1653913370, 1653902570,
];

const res = Object.values(
  times
    .map((t) => new Date(t * 1000).getHours())
    .reduce((r, t) => {
      r[t] ??= { hour: t, occurs: 1 };
      r[t].occurs  = 1;
      return r;
    }, {})
);

console.log(res);

Other relevant documentations:

CodePudding user response:

Create new object. Loop over all times, for example with for each. Use Date class like this new Date(epoch * 1000).getHours() and store that time. Check if key your_hour exists on new object. If it doesn't, push it like myResult[your_hour] = {hour: your_hour, occurances: 1}. If it does exist, then add to that object like so myResult[your_hour].occurances = myResult[your_hour].occurances 1;. That's usually the approach I use but there's multiple solutions to this.

  • Related