如何用filter和some根据对象数组过滤并排除指定事件?
搞定事件数组的过滤需求
嘿,我看你已经尝试用filter和some来实现过滤,但逻辑上有点小问题,导致没得到预期结果。我来帮你梳理下:
你的代码问题出在哪?
你写的filtered_events.some(f => r.summary !== f.summary)逻辑是反的——它的意思是「只要过滤列表里有任意一个项的summary和当前事件不一样,就保留这个事件」。哪怕这个事件明明在要过滤的列表里,只要有其他过滤项和它不同,它就会被留下来,这显然不是你想要的。
另外,你还漏了一个关键匹配条件:toFilterEvents里的每个项是**同时包含startDate和summary**的,你需要同时匹配这两个字段,才算要排除的事件,不能只看summary哦!
正确的实现代码
我们调整下逻辑,用filter遍历原数组,然后判断当前事件不在过滤列表的匹配项中:
filterExistingEvents(filtered_events) { const filteredResult = this.events.filter(event => { // 判断:过滤列表中没有任何一项同时匹配当前事件的日期和标题 return !filtered_events.some(filterItem => { return event.start.date === filterItem.startDate && event.summary === filterItem.summary; }); }); console.log('events after filter', filteredResult, this.events); return filteredResult; } // 调用时传入你的toFilterEvents数组 this.filterExistingEvents(toFilterEvents);
逻辑拆解
filter会遍历this.events里的每一个事件,只保留返回true的项!filtered_events.some(...):如果过滤列表里找不到任何一个项和当前事件的start.date、summary完全匹配,就返回true,也就是保留这个事件- 同时匹配日期和标题,能避免因为重名事件(比如不同日期的同名活动)被误过滤的情况
用你提供的测试数据跑这段代码,就能得到你期望的结果啦!
内容的提问来源于stack exchange,提问作者kartik
相关产品推荐
相关产品推荐

