gpt4 book ai didi

javascript - 如何获取数组中每个月的最新时间戳

转载 作者:行者123 更新时间:2023-11-30 19:16:20 24 4
gpt4 key购买 nike

我有一个数组,里面有一堆对象和一些键/值对 + 时间戳(moment.js 格式的时间戳)。我总共有 12 个月的许多时间戳,需要获取每个月的最后一个时间戳并删除其他对象。

其实我什至不知道如何开始。我已经使用 _.sortBy 按日期对数组进行排序,但不知道如何继续。

array1 = [
{name:name1,timestamp:2018-09-15T07:00:00.0},
{name:name2,timestamp:2018-09-15T12:00:00.0},
{name:name3,timestamp:2018-09-28T05:00:00.0},
{name:name4,timestamp:2018-09-30T01:00:00.0},
{name:name5,timestamp:2018-10-02T10:00:00.0},
{name:name6,timestamp:2018-10-02T11:00:00.0},
{name:name7,timestamp:2018-10-15T07:00:00.0},
{name:name8,timestamp:2018-12-05T08:00:00.0},
{name:name9,timestamp:2018-12-05T09:00:00.0},
{name:name10,timestamp:2018-12-05T10:00:00.0}
]

预期结果是

array1 = [
{name:name4,timestamp:2018-09-30T01:00:00.0},
{name:name7,timestamp:2018-10-15T07:00:00.0},
{name:name10,timestamp:2018-12-05T10:00:00.0}
]

最佳答案

reduce 数组为以月份为键的对象,每次找到它们时都会覆盖它们的键,然后您的结果就是 Object.values 数组:

const array1 = [
{ name: "name1", timestamp: "2018-09-15T07:00:00.0" },
{ name: "name2", timestamp: "2018-09-15T12:00:00.0" },
{ name: "name3", timestamp: "2018-09-28T05:00:00.0" },
{ name: "name4", timestamp: "2018-09-30T01:00:00.0" },
{ name: "name5", timestamp: "2018-10-02T10:00:00.0" },
{ name: "name6", timestamp: "2018-10-02T11:00:00.0" },
{ name: "name7", timestamp: "2018-10-15T07:00:00.0" },
{ name: "name8", timestamp: "2018-12-05T08:00:00.0" },
{ name: "name9", timestamp: "2018-12-05T09:00:00.0" },
{ name: "name10", timestamp: "2018-12-05T10:00:00.0" }
];

const result = array1.reduce((acc, curr) => {
const month = new Date(curr.timestamp).getMonth() + 1;
acc[month] = curr;
return acc;
}, {});

console.log(Object.values(result));

关于javascript - 如何获取数组中每个月的最新时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com