Javascript Check if Two Array contain Common Elements

Check if two Arrays contain common Elements Example; In this tutorial you will learn How to find if two arrays contain a common item in Javascript;

Check if Arrays contain common Elements Using Array.some

To check if two arrays in JavaScript contain common elements we can use Array.some method with Array.includes methods. Array.some will return true If there is at least 1 common element.

const arr1 = ['javascript', 'jquery', 'vue'];
const arr2 = ['javascript', 'jquery'];

const contains = arr1.some(element => {
  return arr2.includes(element);
});

console.log(contains); // true

Check if Arrays contain common Elements using indexOf

To check if two arrays in JavaScript contain common elements we can use Array.some method with Array.indexOf methods.

The indexOf method takes a value and checks if it’s contained in an array. If it is, the index of the element is returned, otherwise -1 is returned.

const arr1 = ['javascript', 'jquery', 'vue'];
const arr2 = ['javascript', 'jquery'];

const contains = arr1.some(element => {
  return arr2.indexOf(element) !== -1;
});

console.log(contains); // true

Hope these example help you.