Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
Reducir matriz en javascript basado en dos condiciones

Digamos que tenemos una matriz de objetos como:

 [ { 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" }, ]

Entonces, mi propósito es reducir la matriz en javascript para que el resultado sea -> para cada Id para cada día para tener la última hora como:

 [ { 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" }, ]

Por favor, ¿puedes ayudar con esto? Gracias por adelantado

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede lograr fácilmente el resultado usando 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!