为了账号安全,请及时绑定邮箱和手机立即绑定

Angular 如何检查 2 个数组中的重叠值?

Angular 如何检查 2 个数组中的重叠值?

萧十郎 2021-10-29 15:56:38
我想检查 2 个数组中的重叠值场景一:cuisineA = [a,b,c];cuisineB = [a,b,c,d,e,f];将返回一个布尔值isOverlap = true场景2:cuisineA = [a,b,c];cuisineB = [d,e,f];将返回一个布尔值isOverlap = false目前我的代码看起来像这样const overlapCuisines = this.cuisineA.filter(      cuisine => this.cuisineB.indexOf(cuisine) < 0    );this.isOverlap = overlapCuisines.length > 0;然而,当它在场景 2 中时,overlapCuisines 将包含值 [a,b,c],因此 isOverlap = true 当它应该是 false 时。我应该如何编码以正确显示它?感谢你的帮助!
查看完整描述

3 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

使用集合交集

let isOverlap = !!((new Set(A)).intersection(new Set(B)))

注意:这是伪代码


查看完整回答
反对 回复 2021-10-29
?
侃侃无极

TA贡献2051条经验 获得超10个赞

如果项目的顺序不重要,则可以使用Array.some()方法。


var cuisineA = ["a","b","c"];

var cuisineB = ["a","b","c","d","e","f"];


var isOverlap = cuisineA.some(value => cuisineB.includes(value));


console.log(isOverlap);



cuisineA = ["a","b","c"];

cuisineB = ["d","e","f"];


isOverlap = cuisineA.some(value => cuisineB.includes(value));


console.log(isOverlap);


查看完整回答
反对 回复 2021-10-29
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

尝试这样的事情。


const overlapCuisines = this.cuisineA.filter(cuisine => this.cuisineB.indexOf(cuisine) !== -1);

this.isOverlap = overlapCuisines.length > 0 ? true : false;

或者


this.isOverlap = Boolean(overlapCuisines.length > 0) ;


查看完整回答
反对 回复 2021-10-29
  • 3 回答
  • 0 关注
  • 134 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信