Swift中按用户ID筛选并保留对应距离最快时间的实现
问题描述
现有一个结构如下的对象数组:
{ id: String, userId: String, distance: Number, time: Number }
数组中同一userId可能存在同一距离的多条记录,示例如下:
[ { id: "1", userId: "1", distance: 100, time: 18.7 }, { id: "2", userId: "1", distance: 100, time: 18.5 }, { id: "3", userId: "2", distance: 100, time: 18.2 }, { id: "4", userId: "2", distance: 200, time: 41.0 }, ]
需要对数组做以下处理:
- 筛选出指定距离的记录
- 每个
userId仅保留该距离下最快时间(time值最小)的记录 - 最终结果按
time从小到大排序
已知可以用.filter()筛选距离、.sort()排序时间,但不清楚如何限制每个userId仅保留一条记录。
解决方案
可以通过分组+筛选最优值的方式实现,以下是JavaScript的具体实现:
const records = [ { id: "1", userId: "1", distance: 100, time: 18.7 }, { id: "2", userId: "1", distance: 100, time: 18.5 }, { id: "3", userId: "2", distance: 100, time: 18.2 }, { id: "4", userId: "2", distance: 200, time: 41.0 }, ]; const targetDistance = 100; // 1. 先筛选出目标距离的所有记录 const distanceFiltered = records.filter(item => item.distance === targetDistance); // 2. 按userId分组,只保留每个用户该距离下的最快记录 const bestRecordsMap = {}; distanceFiltered.forEach(record => { const currentBest = bestRecordsMap[record.userId]; // 如果该用户还没有记录,或者当前记录的时间更快,就更新 if (!currentBest || record.time < currentBest.time) { bestRecordsMap[record.userId] = record; } }); // 3. 将分组后的对象转换为数组,并按时间从小到大排序 const finalResult = Object.values(bestRecordsMap).sort((a, b) => a.time - b.time); console.log(finalResult);
代码说明:
- 用
.filter()快速筛选出指定距离的记录,缩小处理范围 - 用对象
bestRecordsMap存储每个用户的最优记录,userId作为键,每次遍历比较时间,保留更小的那条 - 最后通过
Object.values()将对象转为数组,再用.sort()按时间升序排序,得到最终结果
运行后输出结果:
[ { id: "3", userId: "2", distance: 100, time: 18.2 }, { id: "2", userId: "1", distance: 100, time: 18.5 }, ]
内容的提问来源于stack exchange,提问作者J. Holliday
相关产品推荐
相关产品推荐

