How to Check If an Array Contains All Elements of Another Array in JavaScript?

Find out how you can check if all values in the first array exist in the second using JavaScript

In this post, we will look at different ways to check if every element of the first array exists in the second array.

Using every()

We can use the Array.prototype.every() method (which was introduced in ES5) to check whether all elements in the array pass the test implemented by the provided function. We can use that with Array.prototype.includes() (which was introduced in ES7) like so:

// ES7+
const arr1 = [ 1, 2, 3 ];
const arr2 = [ 3, 5, 4, 2, 7, 0, 1, 10 ];

console.log(arr1.every(elem => arr2.includes(elem))); // output: true

Now, let's look at an example where one of the elements of arr1 does not exist in arr2:

// ES7+
const arr1 = [ 1, 2, 16 ];
const arr2 = [ 3, 5, 4, 2, 7, 0, 1, 10 ];

console.log(arr1.every(elem => arr2.includes(elem))); // output: false

If you don't plan to support ES7, then you can achieve the same in ES5 using indexOf() with every() like so:

// ES5+
console.log(arr1.every(elem => arr2.indexOf(elem) > -1));

Using a for Loop With indexOf()

If you don't plan on supporting ES5, you could opt for using a simple for loop with indexOf() to check if all elements of arr1 exist in arr2 like so:

const arr1 = [ 1, 2, 3 ];
const arr2 = [ 3, 5, 4, 2, 7, 0, 1, 10 ];

let hasAllElems = true;

for (let i = 0; i < arr1.length; i++){
    if (arr2.indexOf(arr1[i]) === -1) {
        hasAllElems = false;
        break;
    }
}

console.log(hasAllElems); // output: true

Using the same code, let's look at an example where one of the elements of arr1 does not exist in arr2:

const arr1 = [ 1, 2, 16 ];
const arr2 = [ 3, 5, 4, 2, 7, 0, 1, 10 ];

let hasAllElems = true;

for (let i = 0; i < arr1.length; i++){
    if (arr2.indexOf(arr1[i]) === -1) {
        hasAllElems = false;
        break;
    }
}

console.log(hasAllElems); // output: false

We can also create a function for this like so:

function arrayContainsAll(needle, haystack) {
    for (let i = 0; i < needle.length; i++){
        if (haystack.indexOf(needle[i]) === -1) {
            return false;
        }
    }

    return true;
}

const result1 = arrayContainsAll([ 1, 2, 3 ], [ 3, 5, 4, 2, 7, 0, 1, 10 ]);
const result2 = arrayContainsAll([ 1, 2, 16 ], [ 3, 5, 4, 2, 7, 0, 1, 10 ]);

console.log(result1); // output: true
console.log(result2); // output: false

Hope you found this post useful. It was published . Please show your love and support by sharing this post.