0

As per question title, I'm using:

Array.prototype.containsAny = function (otherArray) {
  for (let i = 0; i < otherArray.length; i++) 
     if (this.includes(otherArray[i])) 
       return true;

  return false;
};


let a1 =  [3, 5, 9];
let a2 = [4, 5];
a1.containsAny(a2);

Is there a better way?

RedDragon
  • 2,080
  • 2
  • 26
  • 42
  • 1
    `Array#includes` is a _O(n)_ operation compared to `Set#has` which is _O(1)_ - If you're doing this as a repeated operation, the whitelist should be made into a Set first. – Mulan Jan 23 '19 at 16:22

1 Answers1

1

You can use some and includes.

let a1 =  [3, 5, 9];
let a2 = [4, 5];

function containsAny(a1,a2){
  return a1.some(e=> a2.includes(e))
}

console.log(containsAny(a1,a2))
console.log(containsAny(a1, [1,2]))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60