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},        
];


幕布斯6054654
浏览 851回答 1
1回答

BIG阳

var&nbsp;arr&nbsp;=&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;{name:&nbsp;"袜子",&nbsp;timestamp:&nbsp;1537243392}, &nbsp;&nbsp;&nbsp;&nbsp;{name:&nbsp;"月饼",&nbsp;timestamp:&nbsp;1537243369}, &nbsp;&nbsp;&nbsp;&nbsp;{name:&nbsp;"月饼",&nbsp;timestamp:&nbsp;1537243411}, &nbsp;&nbsp;&nbsp;&nbsp;{name:&nbsp;"女鞋",&nbsp;timestamp:&nbsp;1537243241}, &nbsp;&nbsp;&nbsp;&nbsp;{name:&nbsp;"童鞋",&nbsp;timestamp:&nbsp;1537243204}, ];var&nbsp;obj&nbsp;=&nbsp;{}; arr.forEach(v=>{&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!obj[v.name]&nbsp;||&nbsp;obj[v.name].timestamp&nbsp;<&nbsp;v.timestamp)&nbsp;obj[v.name]&nbsp;=&nbsp;v; });console.log(Object.values(obj));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript