gpt4 book ai didi

Javascript根据更大的日期键从数组中删除对象

转载 作者:行者123 更新时间:2023-12-02 21:36:06 26 4
gpt4 key购买 nike

我有一个像这样的数组 -

"formats": [
{
"format": "eBook",
"published": "3/3/2014",
"id": "1234"
},
{
"format": "Paperback",
"published": "19/3/2020",
"id": "123"
},
{
"format": "eBook",
"published": "19/3/2020",
"id": "12345"
}]

我想写一个js过滤函数,它应该根据最新的格式返回我。所以像这样的

"formats": [
{
"format": "Paperback",
"published": "19/3/2020",
"id": "123"
},
{
"format": "eBook",
"published": "19/3/2020",
"id": "12345"
}]

其中 ID 为 1234 的对象被删除,因为具有相同格式的另一个对象(电子书)具有更长的发布日期。

我尝试使用 JS 的过滤功能,但不知何故我把它搞砸了。

最佳答案

const formats = [
{
"format": "eBook",
"published": "3/3/2014",
"id": "1234"
},
{
"format": "Paperback",
"published": "27/3/2020",
"id": "123"
},
{
"format": "Paperback",
"published": "19/3/2020",
"id": "123"
},
{
"format": "eBook",
"published": "19/3/2020",
"id": "12345"
}];

function filterFormats(formats){
const toTime = (date) => new Date(date.replace(/(\d+)\/(\d+)\/(\d+)/, "$2/$1/$3")).getTime();
const data = formats.reduce((a, b) => {
if(b.format+'' in a && toTime(a[b.format].published) > toTime(b.published)) return a;
a[b.format] = b;
return a;
}, {});
return Object.values(data);
}

console.log(filterFormats(formats));

关于Javascript根据更大的日期键从数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60491295/

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