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

如何按年月与Value对列表去重并保留首次出现项?

解决重复记录筛选:保留年月+Value唯一的第一条记录

需求说明

需要过滤包含Timestamp、Value(BigInt类型)、Code的记录数组:

  • 判定重复的依据:年月(从Timestamp提取) + Value的组合相同
  • 每组重复项仅保留第一条,其余剔除
  • 忽略Code字段的取值,非重复记录保持原数组顺序

实现代码

首先定义原始数据数组:

const records = [
  { Timestamp: '2024-01-10 00:20:00', Value: 105.50n, Code: 'I' }, // BigInt类型用n后缀标识
  { Timestamp: '2024-01-15 02:30:00', Value: 105.50n, Code: 'A' },
  { Timestamp: '2024-01-16 10:45:00', Value: 110.50n, Code: 'A' },
  { Timestamp: '2024-02-01 12:20:00', Value: 111.25n, Code: 'I' },
  { Timestamp: '2024-02-04 04:35:00', Value: 111.25n, Code: 'A' },
  { Timestamp: '2024-02-25 02:15:00', Value: 112.25n, Code: 'A' }
];

然后执行过滤逻辑:

const seen = new Set();
const filteredRecords = records.filter(record => {
  // 从Timestamp中提取年月部分(格式:YYYY-MM)
  const yearMonth = record.Timestamp.slice(0, 7);
  // 生成唯一标识:年月 + 转字符串后的BigInt Value
  const key = `${yearMonth}_${record.Value.toString()}`;
  
  if (!seen.has(key)) {
    seen.add(key);
    return true;
  }
  return false;
});

代码解释

  1. 用Set跟踪已处理组合:Set的has和add操作都是O(1)效率,适合快速判断重复项
  2. 提取年月:通过slice(0,7)从YYYY-MM-DD HH:mm:ss格式的Timestamp中截取前7位,得到年月字符串
  3. 生成唯一Key:将年月与转成字符串的Value拼接,确保同一年月下相同Value的记录被判定为重复
  4. filter方法保持顺序:filter遍历原数组时,会按原顺序保留第一个出现的唯一组合记录,自动剔除后续重复项

输出结果

执行后filteredRecords的结果与期望一致:

TimestampValueCode
2024-01-10 00:20:00105.50nI
2024-01-16 10:45:00110.50nA
2024-02-01 12:20:00111.25nI
2024-02-25 02:15:00112.25nA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 18:40:29