我想检查2个数组中的重叠值

方案1:

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。如何编码才能正确显示?感谢您的帮助!

最佳答案

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

关于javascript - Angular 如何检查2个数组中的重叠值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58109367/

10-13 02:21