Languages
[Edit]
EN

JavaScript - check if array contains all elements of another array

0 points
Created by:
Mikolaj
519

In this article, we would like to show you how to check if an array contains all elements of another array in JavaScript.

Practical example

In this example, we create a function that takes in two arguments:

  1. array - the array we want to check whether it has specific elements,
  2. target - an array of elements that the tested array must have.
// ONLINE-RUNNER:browser;

const array1 = [1, 2, 3];
const array2 = [1, 2, 3, 4];
const array3 = [1, 2];

const checkElements = (array, target) => target.every((element) => array.includes(element));

console.log(checkElements(array2, array1)); // true
console.log(checkElements(array3, array1)); // false

Explanation:

The checkElements() function uses two methods:

  1. every() method - to test whether all elements in the target array pass the test implemented by the provided function,
  2. includes() method - to check whether the array includes a certain element.

 

Optimal solution

// ONLINE-RUNNER:browser;

const checkElements = (array, target) => {
    const guardian = new Set();
    for (const entry of target) {
        guardian.add(entry);
    }
    let count = 0;
    for (const entry of array) {
        if (guardian.has(entry)) {
            count += 1;
        }
    }
    return count === guardian.size;
};


// Usage example:

const array1 = [1, 2, 3];
const array2 = [1, 2, 3, 4];
const array3 = [1, 2];

console.log(checkElements(array2, array1));  // true   // checking if array2 contains array1 elements 
console.log(checkElements(array3, array1));  // false  // checking if array3 contains array1 elements 

 

See also

  1. JavaScript - check if array contains any element of another array

References

  1. Array.prototype.every() - JavaScript | MDN
  2. Array.prototype.includes() - JavaScript | MDN

Alternative titles

  1. JavaScript - check if array contains all items of another array
  2. JavaScript - check if array contains all elements from another array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join