如何在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
相关产品推荐
相关产品推荐

