Check if an array contains all the elements of another array in JavaScript
📅August 16, 2021
Today we’ll show you how to check if an array contains all the elements of another array in JavaScript.
In the previous article, we have explained to check if an array contains any element of another array in JavaScript.
Let’s assume that we have two arrays called `array1` and `array2`. Now if we want to check if `array2` contains all the elements of `array1` then we have several ways to verify that. But we will see the best of them.
Checkout more articles on JavaScript
- Execute code only after all images have been loaded in JavaScript
- console methods in JavaScript
- Trim string from the dynamic object in JavaScript
- Remove all whitespace from a string in JavaScript
- Generate a random password using JavaScript
Here, we will use the every() method to tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
const array1 = ['val_1', 'val_2', 'val_3'];
const array2 = ['val_1', 'val_3', 'val_2', 'val_23'];
const array3 = ['val_28', 'val_74', 'val_21'];
const isValidArray2 = array1.every(x => array2.includes(x));
const isValidArray3 = array1.every(x => array3.includes(x));
console.log(isValidArray2); // true
console.log(isValidArray3); // false
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂