Javascript Check if Array Contains all Elements of another Array

Javascript Check if Array Contains all Elements of another Array example; In this tutorial you will learn check if every element of the first array exists in the second array in javascript.

Check if Array has all Elements of Another Array using Array.includes

In javascript we can use Array.prototype.every() method to check whether all elements in the array pass the test implemented by the provided function. We can use that with Array.prototype.includes();

Example 1:

When second array contain all the first array elements;

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

const isContainsAll = arr1.every(element => {
  return arr2.includes(element);
});

console.log(isContainsAll ); // true

Example 2:

When second array not contain all the first array elements;

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

const isContainsAll = arr1.every(element => {
  return arr2.includes(element);
});

console.log(isContainsAll ); // false

Check if Array Contains all Elements of Another Array using Array.indexOf

In javascript we can use Array.prototype.every() method To check if a javascript array contains all of the elements of another array; we can use that with Array.indexOf();

Example 3:

When second array contain all the first array elements;

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

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

console.log(isContainsAll ); // true

Example 4:

When second array not containing all the first array elements;

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

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

console.log(isContainsAll ); // false

Hope you found this post useful.