You need to enable JavaScript to run this app. 使用时间戳实现幂等时如何检测对象数组中的重复时间戳?
优惠活动
大模型
产品
解决方案
定价
更多

使用时间戳实现幂等时如何检测对象数组中的重复时间戳?

数组对象stamp属性重复检测实现方案

推荐使用Set结构实现检测,相比嵌套循环性能更优,时间复杂度为O(n),适配任意长度的数组:

// 检测是否存在重复stamp,存在返回true,不存在返回false
function hasDuplicateStamp(arrayItem: Item[]): boolean {
  const stampSet = new Set(arrayItem.map(item => item.stamp));
  return stampSet.size < arrayItem.length;
}

使用方法

在数据发送前调用该方法,返回true时触发告警终止发送即可:

if (hasDuplicateStamp(arrayItem)) {
  // 自定义告警逻辑,例如弹窗提示、输出错误日志
  console.error('存在重复时间戳,数据发送已阻断');
  return;
}
// 后续正常发送数据的逻辑

如果需要定位具体重复的时间戳值,可以使用Map统计每个stamp的出现次数:

function getDuplicateStampList(arrayItem: Item[]): number[] {
  const stampCountMap = new Map<number, number>();
  arrayItem.forEach(item => {
    const currentCount = stampCountMap.get(item.stamp) || 0;
    stampCountMap.set(item.stamp, currentCount + 1);
  });
  // 筛选所有出现次数大于1的时间戳
  return Array.from(stampCountMap.entries())
    .filter(([stamp, count]) => count > 1)
    .map(([stamp]) => stamp);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:57:03