如何从对象数组中获取每个name对应的最大id值?
按name分组并获取对应最大id的实现方案
核心实现代码
针对你的需求,可通过JavaScript的数组遍历方法快速完成分组与最大值筛选:
var listx = [ { name: 'user:20', id: '1720620993953-0' }, { name: 'user:30', id: '1720621228109-0' }, { name: 'user:30', id: '1720572420832-0' }, { name: 'user:30', id: '1720572410558-0' }, ]; // 生成普通对象格式的结果 const resultObj = listx.reduce((acc, current) => { // 若当前name未记录,或当前id比已存值更大,则更新 if (!acc[current.name] || current.id > acc[current.name]) { acc[current.name] = current.id; } return acc; }, {}); console.log(resultObj); // 输出:{ 'user:20': '1720620993953-0', 'user:30': '1720621228109-0' } // 生成Map类型的结果 const resultMap = new Map(); listx.forEach(item => { const existingId = resultMap.get(item.name); if (!existingId || item.id > existingId) { resultMap.set(item.name, item.id); } }); console.log(resultMap); // 输出:Map(2) { 'user:20' => '1720620993953-0', 'user:30' => '1720621228109-0' }
逻辑说明
- id比较逻辑:你的id格式为
时间戳-0,前半部分是固定长度的数字字符串,直接用字符串比较>即可判断大小(结果和数值比较一致)。 - reduce方法:以空对象为初始值,遍历数组时完成分组与最大值更新,是最简洁的实现方式。
- Map类型适配:如果需要原生Map对象,改用forEach遍历更新即可,逻辑和对象版本一致。
兼容扩展方案
若后续id格式变化(比如后缀不固定、时间戳长度不一致),可拆分id提取时间戳转数值比较:
// 提取id中的时间戳部分 const getTimestamp = id => parseInt(id.split('-')[0], 10); const result = listx.reduce((acc, current) => { const currentTs = getTimestamp(current.id); const existingTs = acc[current.name] ? getTimestamp(acc[current.name]) : -Infinity; if (currentTs > existingTs) { acc[current.name] = current.id; } return acc; }, {});
内容的提问来源于stack exchange,提问作者kpatel23
相关产品推荐
相关产品推荐

