You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于time字段从重复对象数组中获取各path的最新条目

解决方法:保留每个path的最新操作记录

这问题挺常见的,我来给你捋捋怎么处理~核心目标就是对每个重复的path,只保留time最大(也就是最新)的那条记录,下面给你两种常用的JavaScript实现方式:

方法一:使用Array.reduce()(简洁高效)

reduce方法能帮我们遍历数组的同时,维护一个以path为键的对象,每次遇到相同path就对比时间,自动保留更新的那条:

const operations = [ 
  {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 latestOperations = Object.values(
  operations.reduce((acc, curr) => {
    // 如果当前path不在缓存里,或者当前条目的时间比已存的更新,就替换
    if (!acc[curr.path] || curr.time > acc[curr.path].time) {
      acc[curr.path] = curr;
    }
    return acc;
  }, {})
);

console.log(latestOperations);

运行后会得到每个path的最新记录:

[
  {time: 1526577280000, 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"}
]

方法二:先排序再去重(直观易懂)

如果觉得reduce逻辑有点绕,也可以先把数组按time从大到小排序,然后遍历数组,只保留第一次出现的path:

// 先按时间降序排序,最新的条目排在最前面
const sortedOperations = [...operations].sort((a, b) => b.time - a.time);

const seenPaths = new Set();
const latestOperations = sortedOperations.filter(item => {
  if (!seenPaths.has(item.path)) {
    seenPaths.add(item.path);
    return true;
  }
  return false;
});

console.log(latestOperations);

这个方法的结果和上面完全一致,优点是逻辑直白,新手也能快速理解。

两种方法对比

  • reduce方法:时间复杂度O(n),只需要遍历一次数组,性能更优,适合处理大数据量的场景。
  • 排序+过滤方法:时间复杂度O(n log n)(主要来自排序的开销),但可读性更强,逻辑一目了然。

你可以根据自己的实际场景选合适的方式~

内容的提问来源于stack exchange,提问作者surazzarus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:17:58