Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
How to calculate the number of occurrences and assign them to the appropriate place?

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!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  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:

  • Array.prototype.map
  • Object.values
  • Nullish coalescing operator (??)
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda