Skip to content Skip to sidebar Skip to footer

Get Latest Object With Oldest Date From Array Of Objects With Date Object

Here's what my array looks like [ { name: 'myname', date: dateObj, value: 2 }, { name: 'othername', date: dateObj, value: 3 }, { name: 'newname', date: dateObj, value: 5 }, ] D

Solution 1:

You can use Array.reduce() to iterate the array, and on each iteration pick the object with the oldest date:

const data = [
 { name: "myname", date: newDate(2016, 5, 1), value: 2 },
 { name: "othername", date: newDate(2018, 6, 1), value: 3 },
 { name: "newname", date: newDate(2017, 12, 1), value: 5 },
];

const result = data.reduce((r, o) => o.date < r.date ? o : r);

console.log(result);

Solution 2:

Yes. The Array must be pre-sorted. :)

In other words, No. Without iterating the whole Array, there seems no way to find out the Object with oldest date. We need to iterate the Array.

Solution 3:

This should do what you want, if we call your array myArray:

myArray.sort((objA, objB) => objA.date.getTime() - objB.date.getTime())[0];

Post a Comment for "Get Latest Object With Oldest Date From Array Of Objects With Date Object"