Check if Multiple Values Exist in Array in JavaScript
JavaScript has many ways to check if multiple values exist in an array. One way to accomplish this is to use the every() method and include() method of the native array object.
<script> let arr1 = [1, 2, 3]; let arr2 = [4, 2, 1, 3, 5]; let result = arr1.every((val) => arr2.includes(val)); console.log(result); // true </script>
In the above example, we define two arrays arr1 and arr2. Then, we use the every() method on arr1 to check if every element in that array exists in arr2 using the includes() method.
The every() method returns a boolean based on the condition we provide, which in this case is if every element in arr1 is included in arr2. The result is logged to the console.
How to check if multiple values exist in array #
- Using a loop to check for each value.
<script> let arr1 = [4, 2, 1, 3, 5]; let arr2 = [1, 2, 3]; let status = true; for (let i = 0; i < arr2.length; i++) { if(!arr1.includes(arr2[i])) { status = false; break; } } console.log(status); // true </script>
- Using the every() method with the includes() method.
<script> let arr1 = [4, 2, 1, 3, 5]; let arr2 = [1, 2, 3]; let status = arr2.every(item => arr1.includes(item)); console.log(status); // true </script>
- Using the filter() method to create a new array with the matching values, and comparing the length to the original array.
<script> let arr1 = [4, 2, 1, 3, 5]; let arr2 = [1, 2, 3]; const matchingArray = arr1.filter(item => arr2.includes(item)); const status = matchingArray.length === arr2.length; console.log(status); // true </script>
save
listen
AI Answer
Check if Multiple Values Exist in Array in JavaScript
0
JavaScript has many ways to check if multiple values exist in an array. One way to accomp…
asked
Apu
0 answers
2915
JavaScript has many ways to check if multiple values exist in an array. One way to accomp…
Answer Link
answered
Apu