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

山姆·洛克

我有一个对象数组,并且有一些重复的对象

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 }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章