gpt4 book ai didi

javascript - 根据创建时间从对象数组中删除重复项

转载 作者:行者123 更新时间:2023-12-05 03:40:22 25 4
gpt4 key购买 nike

我有一个对象数组,其中有一些重复的对象

const data = [
{
"id": "1011",
"name": "abc",
"Dob": "3/2/11",
"timeCreated": "16:03:41"
},
{
"id": "1012",
"name": "xys",
"Dob": "6/5/12",
"timeCreated": "01:05:21"
},
{
"id": "1011",
"name": "xyz",
"Dob": "3/2/11",
"timeCreated": "17:03:41"
},
{
"id": "1011",
"name": "xyz",
"Dob": "3/2/11",
"timeCreated": "15:03:41"
}
]

我正在使用 some() 删除数组中的重复项

let arr = [];
data.forEach(obj => {
if (!arr .some(o => o.id === obj.id)) {
arr.push({ ...obj})
}
});

我需要帮助过滤它并只保留基于“timeCreated”的最新对象

所以数据看起来像这样:

{
"id": "1012",
"name": "xys",
"Dob": "6/5/12",
"timeCreated": "01:05:21"
},
{
"id": "1011",
"name": "xyz",
"Dob": "3/2/11",
"timeCreated": "17:03:41"
},
]

最佳答案

你可以这样做:

const data = 
[ { id: '1011', name: 'abc', Dob: '3/2/11', timeCreated: '16:03:41' }
, { id: '1012', name: 'xys', Dob: '6/5/12', timeCreated: '01:05:21' }
, { id: '1011', name: 'xyz', Dob: '3/2/11', timeCreated: '17:03:41' }
, { id: '1011', name: 'xyz', Dob: '3/2/11', timeCreated: '15:03:41' }
]

const arr = data.reduce((result,obj)=>
{
let row = result.find(x=>x.id===obj.id)
if (!row)
result.push({...obj})
else if (row.timeCreated < obj.timeCreated)
Object.assign(row,obj)
return result
},[])

console.log( arr )
.as-console-wrapper {max-height: 100%!important;top:0 }

关于javascript - 根据创建时间从对象数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68171261/

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