从具有日期对象的对象数组中获取具有最早日期的最新对象 [英] Get latest object with oldest date from array of objects with date object
本文介绍了从具有日期对象的对象数组中获取具有最早日期的最新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的数组的样子
[
{ name: "myname", date: dateObj, value: 2 },
{ name: "othername", date: dateObj, value: 3 },
{ name: "newname", date: dateObj, value: 5 },
]
日期是本地日期对象.
获取日期最旧的一个对象的最聪明方法是什么?有没有比遍历整个数组更好的方法了?
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?
推荐答案
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);
这篇关于从具有日期对象的对象数组中获取具有最早日期的最新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文