Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the newest date with reduce in javascript

I have deliveries object as below. And I would like to find the object whose deliveryDate is the newest.

const deliveries = [
        { id: 'HgP6cJB01', deliveryDate: '2022-10-05T11:06:20.208Z', url: 'some link1' },
        { id: 'HgP6cJB02', deliveryDate: '2022-10-15T12:06:21.208Z', url: 'some link2' },
        { id: 'HgP6cJB03', deliveryDate: '2022-10-20T13:06:22.208Z', url: 'some link3' }
      ]

I would like to compare the objects in the array and get one with newest date deliveries[2]

My approach below returns nothing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

deliveries?.reduce((curr, acc) => {
          if (curr.deliveryDate < acc.deliveryDate) {
            return { ...acc };
          }
        })

>Solution :

First you need to convert it to new Date() so you can compare them.

const deliveries = [{ id: 'HgP6cJB03', deliveryDate: '2022-10-20T13:06:22.208Z', url: 'some link3' }, { id: 'HgP6cJB01', deliveryDate: '2022-10-05T11:06:20.208Z', url: 'some link1' }, { id: 'HgP6cJB02', deliveryDate: '2022-10-15T12:06:21.208Z', url: 'some link2' }, ]

//When curr is newest we retun {...curr} if it's not we just return current accumulator {...acc}
const newest = deliveries.reduce((acc, curr) => new Date(curr.deliveryDate) > new Date(acc.deliveryDate) ? {...curr} : {...acc});
console.log(newest);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading