JS/TS数组按城市去重并保留最新updated日期记录实现求助
你可以通过「按城市分组+同组取最新更新时间」的逻辑实现需求,完整实现代码如下:
// 过滤出名称匹配搜索词的开发者 const matchedDevs = devs.filter(temp => temp.name.toLowerCase().includes(searchTerm.toLowerCase()) ); // 用Map存储每个城市对应的最新地址 const cityLatestMap = new Map<string, IAddress>(); for (const dev of matchedDevs) { const currentAddr = dev.addr; const city = currentAddr.city; // 该城市还没有记录,直接存入 if (!cityLatestMap.has(city)) { cityLatestMap.set(city, currentAddr); continue; } // 已有同城市记录,比较更新时间,保留最新的 const savedAddr = cityLatestMap.get(city)!; const currentTime = new Date(currentAddr.updated).getTime(); const savedTime = new Date(savedAddr.updated).getTime(); if (currentTime > savedTime) { cityLatestMap.set(city, currentAddr); } } // 转换为最终结果数组,如果需要和你之前输出结构一致的{addr: xxx}格式,就用下面注释的写法 const address: IAddress[] = Array.from(cityLatestMap.values()) // const address = Array.from(cityLatestMap.values()).map(addr => ({addr}))
逻辑说明
- 把你原先的
indexOf > -1替换为includes,语义更清晰,执行效果完全相同 - 遍历所有匹配的记录时,用城市作为Map的唯一key,遇到同城市的记录就把
updated字段转为时间戳比较大小,只保留时间最新的记录 - 最后把Map中存储的所有值转为数组,就是按城市去重、只保留最新记录的结果
内容的提问来源于stack exchange,提问作者Glen
相关产品推荐
相关产品推荐

