EN
JavaScript - check if array contains all elements of another array
0
points
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:
array- the array we want to check whether it has specific elements,target- an array of elements that the testedarraymust 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:
every()method - to test whether all elements in thetargetarray pass the test implemented by the provided function,includes()method - to check whether the array includes a certainelement.
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