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

我想检查 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 时。我应该如何编码以正确显示它?感谢你的帮助!


萧十郎
浏览 135回答 3
3回答

饮歌长啸

使用集合交集let&nbsp;isOverlap&nbsp;=&nbsp;!!((new&nbsp;Set(A)).intersection(new&nbsp;Set(B)))注意:这是伪代码

侃侃无极

如果项目的顺序不重要,则可以使用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);

哈士奇WWW

尝试这样的事情。const overlapCuisines = this.cuisineA.filter(cuisine => this.cuisineB.indexOf(cuisine) !== -1);this.isOverlap = overlapCuisines.length > 0 ? true : false;或者this.isOverlap = Boolean(overlapCuisines.length > 0) ;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript