Reputation: 539
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 },
]
Dates are native date objects.
What would be the smartest way to get the one object with the oldest date? Is there a better way than sorting the whole array by looping through?
Upvotes: 7
Views: 4883
Reputation: 18249
This should do what you want, if we call your array myArray
:
myArray.sort((objA, objB) => objA.date.getTime() - objB.date.getTime())[0];
Upvotes: 1
Reputation: 191946
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: new Date(2016, 5, 1), value: 2 },
{ name: "othername", date: new Date(2018, 6, 1), value: 3 },
{ name: "newname", date: new Date(2017, 12, 1), value: 5 },
];
const result = data.reduce((r, o) => o.date < r.date ? o : r);
console.log(result);
Upvotes: 15
Reputation: 85
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.
Upvotes: 1