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?

1
  • 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. Commented Jan 23, 2019 at 16:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.