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

如何在JavaScript中从对象数组按日期提取每个用户的最新交易记录

实现方案

核心思路

  • 以userid作为用户唯一标识,用Map结构存储每个用户对应的最新交易记录
  • 遍历原数组时对比同用户下的交易日期,保留日期最新的条目
  • 最后将Map中存储的所有值转为数组即为最终结果

注意:如果你的日期字段不是ISO标准格式,需要先自行调整日期转时间戳的逻辑,确保日期大小对比准确。

代码实现(JavaScript)

// 示例输入数组
const transactions = [
    {
        "id": "1",
        "amount": 100,
        "date": "2021-12-02T05:24:24.215Z",
        "userid": "uid",
        "username": "username",
    },
    {
        "id": "2",
        "amount": 150,
        "date": "2021-12-02T05:24:24.215Z",
        "userid": "uid1",
        "username": "username1",
    },
    {
        "id": "3",
        "amount": 200,
        "date": "2021-11-02T05:24:24.215Z",
        "userid": "uid1",
        "username": "username1",
    }
];

// 存储每个用户最新记录的Map
const latestTransMap = new Map();

transactions.forEach(trans => {
    const currentUserId = trans.userid;
    const currentDateTs = new Date(trans.date).getTime();
    // 判断Map中是否已有该用户的记录
    if (!latestTransMap.has(currentUserId)) {
        latestTransMap.set(currentUserId, trans);
    } else {
        const existTrans = latestTransMap.get(currentUserId);
        const existDateTs = new Date(existTrans.date).getTime();
        // 若当前记录日期更新则替换
        if (currentDateTs > existDateTs) {
            latestTransMap.set(currentUserId, trans);
        }
    }
});

// 转为结果数组
const result = Array.from(latestTransMap.values());
console.log(result);

输出结果

[
  {
    id: '1',
    amount: 100,
    date: '2021-12-02T05:24:24.215Z',
    userid: 'uid',
    username: 'username'
  },
  {
    id: '2',
    amount: 150,
    date: '2021-12-02T05:24:24.215Z',
    userid: 'uid1',
    username: 'username1'
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:04