我需要从多个条目中获取最近的条目。
let items = [{Fruit: "Apple",date: 1592809121000},
{Fruit: "Orange",date: 1592564167000},
{Fruit: "Apple",date: 1592566351000},
{Fruit: "Orange",date: 1592809121000},
{Fruit: "Apple",date: 1592564167000},
{Fruit: "Apple",date: 1593153998000},
{Fruit: "Orange",date: 1592893249000},
{Fruit: "Grapes",date: 1592565214000}]
预期输出:
let items = [{
Fruit: "Apple",
date: recent entry
}, {
Fruit: "Orange",
date: recent entry
}, {
Fruit: "Grapes",
date: recent entry
}]
尝试用代码对日期进行排序,但它是在所有水果中排序,但我只想在特定水果中进行排序,以获取带有时间戳的最新条目并从数组中删除其他条目
// Sort by date and show recent first
items = items.sort(function(a, b) {
return (new Date(b.date))- (new Date(a.date));
});
最佳答案
您可以减少数组并只取每种水果中较大的日期。
let array = [{ Fruit: "Apple", date: 1592809121000 }, { Fruit: "Orange", date: 1592564167000 }, { Fruit: "Apple", date: 1592566351000 }, { Fruit: "Orange", date: 1592809121000 }, { Fruit: "Apple", date: 1592564167000 }, { Fruit: "Apple", date: 1593153998000 }, { Fruit: "Orange", date: 1592893249000 }, { Fruit: "Grapes", date: 1592565214000 }],
result = Object.values(array.reduce((r, o) => {
if (!r[o.Fruit] || r[o.Fruit].date < o.date) r[o.Fruit] = o;
return r;
}, {}));
console.log(result);
关于javascript - 根据一个属性和日期对象的值对数组进行排序,以使用 JavaScript 获取最近的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62692108/