The includes()
method in JavaScript only checks for the presence of a single value in an array. If you want to check for the presence of multiple values in an array, you can use the every()
method in combination with the includes()
method.
JavaScript array includes multiple values example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const array = [1, 2, 3, 4, 5];
const valuesToCheck = [5, 4];
const hasAllValues = valuesToCheck.every(value => array.includes(value));
console.log(hasAllValues);
</script>
</body>
</html>
Output:
Another way to check if an array contains multiple values in JavaScript.
The every()
method is used in combination with the indexOf()
method to check if every element in array_a
is present in array_b
.
const array_a = [1, 2, 3];
const array_b = [3, 2, 1];
const success = array_a.every(function(val) {
return array_b.indexOf(val) !== -1;
});
console.log(success); // true
Comment if you have any doubts or suggestions on this Js array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version