Different ways in JavaScript to check if all elements of one array are in a second array

JavaScript program to check if all elements of one array are in a second array :

JavaScript comes with a couple of different array methods. You don’t have to loop through each elements of an array to check if they are in a second array. In this post, I will show you different ways to check if all elements of an array is in another way or not.

If you have any other method in mind, drop a comment.

Using filter :

Using filter, we can filter out the elements of an array based on a specific condition. It takes one function as its parameter and returns only the elements that satisfies the function.

const firstArr = [1,2,3,4];
const secondArr = [1,2,3,4,5,6];

if(firstArr.filter(e => secondArr.indexOf(e) !== -1).length === firstArr.length){
  console.log("yes");
}else{
  console.log("no");
}

Here, we are using filter to get all elements of firstArr those exists also in secondArr. If the returned array length is equal to the length of firstArr, it implies that all elements of firstArr are in secondArr. We are using indexOf to check if an element exists in an array or not.

Using filter and includes :

In the above program, we have used indexOf to check if one element exists in an array or not. We can also use includes() instead :

const firstArr = [1,2,3,4];
const secondArr = [1,2,3,4,5,6];

if(firstArr.filter(e => secondArr.includes(e)).length === firstArr.length){
  console.log("yes");
}else{
  console.log("no");
}

Using map() :

map() takes one function as its parameter, calls that function on each element of the array and creates one new array.

const firstArr = [1,2,3,4];
const secondArr = [1,2,3,4,5,6];


if(!firstArr.map(i => secondArr.includes(i)).includes(false)){
  console.log("yes");
}else{
  console.log("no");
}

In this example, map() takes one function that checks if the second array includes the current value or not. includes() returns one boolean. So, the final array will be an array of boolean values. We are using one more includes to this array to check if it contains any false value. If it contains false, means not all elements are in the second array.

Using every() :

every() method takes one function and checks every element in an array with that function. It returns one boolean value. Even if atleast one element fails, it returns false.

const firstArr = [1,2,3,4];
const secondArr = [1,2,3,4,5,6];

if(firstArr.every(e => secondArr.indexOf(e) >= 0)){
  console.log("yes");
}else{
  console.log("no");
}

We are using indexOf to find if one element exists in an array or not. You can also use includes instead.