Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

253
Vistas
Reduce array in javascript based on two conditions

Lets say we have an array of object like:

[ 
    { id: 1, time: "2021-05-02 10:12:45.123" },
    { id: 1, time: "2021-05-02 11:12:45.123" },
    { id: 1, time: "2021-05-02 12:12:45.123" },
    { id: 2, time: "2021-05-02 05:12:45.123" },
    { id: 1, time: "2021-05-01 12:12:45.123" },
    { id: 2, time: "2021-05-01 05:12:45.123" },
    { id: 2, time: "2021-05-01 04:12:45.123" },
    { id: 3, time: "2021-05-01 10:12:45.123" },
]

So my purpose is to reduce the array in javascript so the result to be -> for every Id for every day to have the latest time like:

[ 
    { id: 1, time: "2021-05-02 12:12:45.123" },
    { id: 2, time: "2021-05-02 05:12:45.123" },
    { id: 1, time: "2021-05-01 12:12:45.123" },
    { id: 2, time: "2021-05-01 05:12:45.123" },
    { id: 3, time: "2021-05-01 10:12:45.123" },
]

Please can you help with this. Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can easily achieve the result using reduce

const arr = [
  { id: 1, time: "2021-05-02 10:12:45.123" },
  { id: 1, time: "2021-05-02 11:12:45.123" },
  { id: 1, time: "2021-05-02 12:12:45.123" },
  { id: 2, time: "2021-05-02 05:12:45.123" },
  { id: 1, time: "2021-05-01 12:12:45.123" },
  { id: 2, time: "2021-05-01 05:12:45.123" },
  { id: 2, time: "2021-05-01 04:12:45.123" },
  { id: 3, time: "2021-05-01 10:12:45.123" },
];

const result = arr.reduce((acc, curr) => {
  if (acc.length && acc[acc.length - 1].id === curr.id) {
    if (new Date(acc[acc.length - 1].time) < new Date(curr.time)) {
      acc[acc.length - 1] = { ...acc[acc.length - 1], ...curr };
    }
  } else acc.push(curr);
  return acc;
}, []);

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda