如何移除JavaScript数组中的重复项?现有代码返回重复事件需解决
解决返回事件数组重复的问题
你的代码逻辑是筛选未来发生的事件,但最终返回的eventosconboletos出现重复,核心原因是第一个循环生成的eventsWithLowestPrice数组里已经存在重复的事件ID——因为User.getF()返回的events中,可能有多个条目对应同一个id_evento_fk,它们都满足时间条件,导致同一个ID被多次推入数组,后续第二个循环根据这些重复ID查询事件,自然会生成重复的事件对象。
两种去重方案
方案1:在收集事件ID时就避免重复
修改第一个循环的判断逻辑,添加ID存在性检查,确保同一个事件ID只被推入一次:
getAllNew: async (req, res) => { //This code is what gives us only events that are going to happen, and discards the ones in the past. try { const eventsWithLowestPrice = [] const eventosconboletos = [] const events = await User.getF() for (const event of events) { const date1 = stringToDate(event.fecha_fin); const date2 = stringToDate(today); // 新增判断:确保当前ID未在数组中才添加 if (date1 >= date2 && event.hora_fin > my_time && !eventsWithLowestPrice.includes(event.id_evento_fk)) { eventsWithLowestPrice.push(event.id_evento_fk) } } for (const eventWithLowestPrice of eventsWithLowestPrice) { const publication = await Event.getOne(eventWithLowestPrice); eventosconboletos.push(publication) } res.json(eventosconboletos) } catch (error) { console.log(error) res.status(500).json({ msg: 'Error al consultar eventos' }) } },
方案2:对最终的事件数组去重
如果不想修改第一个循环,也可以在返回结果前,基于事件的唯一标识(比如id_evento_fk)对eventosconboletos去重:
getAllNew: async (req, res) => { //This code is what gives us only events that are going to happen, and discards the ones in the past. try { const eventsWithLowestPrice = [] const eventosconboletos = [] const events = await User.getF() for (const event of events) { const date1 = stringToDate(event.fecha_fin); const date2 = stringToDate(today); if (date1 >= date2 && event.hora_fin > my_time) { eventsWithLowestPrice.push(event.id_evento_fk) } } for (const eventWithLowestPrice of eventsWithLowestPrice) { const publication = await Event.getOne(eventWithLowestPrice); eventosconboletos.push(publication) } // 基于id_evento_fk去重,保留最后出现的重复项 const uniqueEvents = [...new Map(eventosconboletos.map(item => [item.id_evento_fk, item])).values()] res.json(uniqueEvents) } catch (error) { console.log(error) res.status(500).json({ msg: 'Error al consultar eventos' }) } },
额外优化建议
推荐用方案1,因为它能减少后续不必要的数据库查询(避免重复查询同一个事件ID),提升性能。
内容的提问来源于stack exchange,提问作者JPcoder
相关产品推荐
相关产品推荐

