js 数组里的对象去重

需求是:如果数组的name相同,就比较下timestamp,哪个比较大保留哪个,小的去掉。数组如下:

var arr = [
    {name: "袜子", timestamp: 1537243392},
    {name: "月饼", timestamp: 1537243369},
    {name: "月饼", timestamp: 1537243411},
    {name: "女鞋", timestamp: 1537243241},
    {name: "童鞋", timestamp: 1537243204},        
];

希望得到的数组结果是:

var finalArr = [
    {name: "袜子", timestamp: 1537243392},
    {name: "月饼", timestamp: 1537243411},
    {name: "女鞋", timestamp: 1537243241},
    {name: "童鞋", timestamp: 1537243204},        
];
阅读 3.7k
4 个回答

一个原始的版本

var arr = [
    {name: "袜子", timestamp: 1537243392},
    {name: "月饼", timestamp: 1537243369},
    {name: "月饼", timestamp: 1537243411},
    {name: "女鞋", timestamp: 1537243241},
    {name: "童鞋", timestamp: 1537243204},
];

var obj = {};
----v1
arr.forEach(v=>{
    obj[v.name] = v;
});

---v2 总是取timestamp最大的;
arr.forEach(v => {
    if (obj[v.name]) {
        if (obj[v.name].timestamp < v.timestamp) {
            obj[v.name] = v;
        }
    } else {
        obj[v.name] = v;
    }
});
console.log(Object.values(obj));




var arr = [
    {name: "袜子", timestamp: 1537243392},
    {name: "月饼", timestamp: 1537243369},
    {name: "月饼", timestamp: 1537243411},
    {name: "女鞋", timestamp: 1537243241},
    {name: "童鞋", timestamp: 1537243204},
];
var obj = {};
arr.forEach(v=>{
    if (!obj[v.name] || obj[v.name].timestamp < v.timestamp) obj[v.name] = v;
});
console.log(Object.values(obj));

这个,如果name数量不多,用桶排序去重应该比较好实现的。
伪码实现如下:

var T={};
for(var i=0;i<arr.length;i++){ // 遍历数组元素
    if( ( T[ arr[i][name] ]== undefined ) || ( arr[i][timestamp] >  T[ arr[i][name] ] ) )
        T[ arr[i][name] ] =  arr[i][timestamp]
    }
}
var finalArr=[];
for( n  in T){   
  var tobj= {name: n,timestamp:T[n]};
  finalArr.push( tobj );
}
arr.sort((a,b)=>{
  var v1=a.name
  var v2=b.name
  if(v1==v2){
    return b.timestamp-a.timestamp
  }
  return v2-v1
})
console.log("11",arr)
var obj=[]
arr = arr.reduce((cur,next) => {
    obj[next.name] ? "" : obj[next.name] = true && cur.push(next);
    return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(arr);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题