我有一系列对象,如下所示,
[
{time: 1526577280000, operationType: "CREATE", path: "users/111"},
{time: 1526563418000, operationType: "DELETE", path: "users/111"},
{time: 1526557418000, operationType: "CREATE", path: "users/111"},
{time: 1526557280000, operationType: "CREATE", path: "users/123"},
{time: 1526557223000, operationType: "CREATE", path: "users/345"},
{time: 1526553596000, operationType: "DELETE", path: "users/222"},
{time: 1526553444000, operationType: "CREATE", path: "users/222"}
]
如何根据最新的timestamp
即time
,仅从重复路径返回最新的单个路径。有些对象具有基于operationType的相同路径,我只想从具有多个相同路径的对象返回最新路径。
答案 0 :(得分:1)
首先,您需要定义条目重复项的时间。我理解它的方式,他们的operationType
和 path
需要相等,但time
可能会有所不同。这给了我们:
const equal = (x, y) => (
x.operationType === y.operationType &&
x.path === y.path
);
现在,在循环所有条目时,我们不一定要检查所有其他条目是否相等。这就是为什么我们会采用不同的方式来跟踪我们的进度。我们将定义一个hash
函数,将对象序列化为可比较的字符串:
const hash = e => [e.operationType, e.path].join("__");
现在,我们可以循环我们的数据一次并检查该条目是第一个哈希,还是比前一个更旧:
const data = [
{time: 1526577280000, operationType: "CREATE", path: "users/111"},
{time: 1526563418000, operationType: "DELETE", path: "users/111"},
{time: 1526557418000, operationType: "CREATE", path: "users/111"},
{time: 1526557280000, operationType: "CREATE", path: "users/123"},
{time: 1526557223000, operationType: "CREATE", path: "users/345"},
{time: 1526553596000, operationType: "DELETE", path: "users/222"},
{time: 1526553444000, operationType: "CREATE", path: "users/222"}
];
const hash = e => [e.operationType, e.path].join("__");
const latestUniques = Object.values(data.reduce(
(map, e) => {
const key = hash(e);
if (!map[key] || map[key].time > e.time) {
map[key] = e;
}
return map;
},
{}
));
console.log(latestUniques);

答案 1 :(得分:0)
尝试这样的事情
array.sort( function(one, two){ return one.time < two.time } )[0].path;