How to check whether an array is subset of another array using JavaScript ?
The task is to check whether an array is a subset of another array with the help of JavaScript. Here are a few techniques discussed.
Approach 1:
- This approach checks whether every element of the second array is present in the first array or not.
Example 1: This example uses the approach as discussed above.
<!DOCTYPE HTML> < html > < head > < title > check whether an array is subset of another array using JavaScript </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = ["GFG", "Geeks", "Portal", "Geek", "GFG_1", "GFG_2"]; var arr2 = ["GFG", "Geeks", "Geek"]; up.innerHTML = "Click on the button to check the subset property."+ "< br >Array1-" + arr1 + "< br >Array2-" + arr2; function GFG_Fun() { res = arr2.every(function(val) { return arr1.indexOf(val) >= 0; }); not = ""; if (!res) { not = "not"; } down.innerHTML = "Array_2 is " + not + " the subset of Array_1"; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Approach 2:
- This approach declares false if some element of second array is not present in first array.
Example 2: This example uses the approach as discussed above.
<!DOCTYPE HTML> < html > < head > < title > check whether an array is subset of another array using JavaScript </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = ["GFG", "Geeks", "Portal", "Geek", "GFG_1", "GFG_2"]; var arr2 = ["GFG", "Geeks", "GeekForGeeks"]; up.innerHTML = "Click on the button to check the subset property."+ "< br >Array1-" + arr1 + "< br >Array2-" + arr2; function GFG_Fun() { res = !arr2.some(val => arr1.indexOf(val) === -1); not = ""; if (!res) { not = "not"; } down.innerHTML = "Array_2 is " + not + " the subset of Array_1"; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: