需求是:如果数组的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},
];
1 回答
BIG阳
TA贡献1859条经验 获得超6个赞
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));
添加回答
举报
0/150
提交
取消