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.
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);