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

255
Views
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 answers
Answer question

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 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!