去除name相同的对象
且保留的是创建时间最早的对象
array.reduce(function(prev, cur, index, arr), initialValue)
callback (执行数组中每个值的函数,包含四个参数)
1、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
2、currentValue (数组中当前被处理的元素)
3、index (当前元素在数组中的索引)
4、array (调用 reduce 的数组)
initialValue (作为第一次调用 callback 的第一个参数。)类似相当于设置初始值
var arr = [
{
name: '李四',
created_at: '2022-05-04 01:54:06',
},
{
name: '李四',
created_at: '2022-03-05 04:52:49',
},
{
name: '李四',
created_at: '2022-08-06 08:02:02',
},
{
name: '王五',
created_at: '2022-07-09 04:52:40',
},
{
name: '王五',
created_at: '2022-07-09 09:07:21',
}
]
let result = arr.reduce((init, item) => {
let index = init.findIndex(itemB => itemB.name === item.name) // 0 0 -1 1
if(index === -1) {
init.push(item)
} else {
if( init[index].created_at > item.created_at ) {
init.splice(index, 1, item)
}
}
return init
}, [])
{name: '李四', created_at: '2022-03-05 04:52:49'}
{name: '王五', created_at: '2022-07-09 04:52:40'}