iBlehhz
iBlehhz

Reputation: 586

Angular How to check for overlap values in 2 arrays?

I would like to check for overlap values in 2 arrays

Scenario 1:

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

will return me a boolean value isOverlap = true

Scenario 2:

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

will return me a boolean value isOverlap = false

Currently my code looks like this

const overlapCuisines = this.cuisineA.filter(
      cuisine => this.cuisineB.indexOf(cuisine) < 0
    );
this.isOverlap = overlapCuisines.length > 0;

However, when it is in scenario 2, overlapCuisines would contain the value [a,b,c] and hence isOverlap = true when it should be false. How should I code it to display it properly? Appreciate your help!

Upvotes: 1

Views: 1195

Answers (3)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Use set intersection

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

Note: this is pseudocode

Upvotes: 1

Nikhil
Nikhil

Reputation: 6641

If order of items isn't important, then Array.some() method can be used.

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);

Upvotes: 3

Poldo
Poldo

Reputation: 1932

Try something like this.

const overlapCuisines = this.cuisineA.filter(cuisine => this.cuisineB.indexOf(cuisine) !== -1);
this.isOverlap = overlapCuisines.length > 0 ? true : false;

Or

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

Upvotes: 2

Related Questions