HomeLanguagesJavascriptHow to check whether an array is subset of another array using...

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. There are a few approaches, we will discuss below:

Approaches:

Approach 1: Using JavaScript array.every() method

This approach checks whether every element of the second array is present in the first array or not.

Example: This example uses the approach discussed above. 

Javascript




// Creating 2 arrays
let arr1 = ["GFG", "Geeks", "Portal",
            "Geek", "GFG_1", "GFG_2"];
             
let arr2 = ["GFG", "Geeks", "Geek"];
 
// Funtion to check subarray
function GFG_Fun() {
    let res = arr2.every(function (val) {
        return arr1.indexOf(val) >= 0;
    });
 
    let not = "";
    if (!res) {
        not = "not";
    }
    // Display the output
    console.log("Array_2 is " + not
        + " the subset of Array_1");
}
 
GFG_Fun();


Output

Array_2 is  the subset of Array_1

Approach 2: Using JavaScript array.some() method

This approach declares false if some element of the second array is not present in the first array.

Example: This example uses the approach discussed above. 

Javascript




// Create input arrays
let arr1 = ["GFG", "Geeks", "Portal",
            "Geek", "GFG_1", "GFG_2"];
 
let arr2 = ["GFG", "Geeks", "GeekForGeeks"];
 
// Function to check subarrays
function GFG_Fun() {
    let res = !arr2.some(val => arr1.indexOf(val) === -1);
    let not = "";
    if (!res) {
        not = "not";
    }
     
    // Display output
    console.log("Array_2 is " + not
        + " the subset of Array_1");
}
 
GFG_Fun();


Output

Array_2 is not the subset of Array_1
RELATED ARTICLES

Most Popular

Dominic
32715 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7092 POSTS0 COMMENTS
Nicole Veronica
12231 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12313 POSTS0 COMMENTS
Shaida Kate Naidoo
7209 POSTS0 COMMENTS
Ted Musemwa
7473 POSTS0 COMMENTS
Thapelo Manthata
7192 POSTS0 COMMENTS
Umr Jansen
7173 POSTS0 COMMENTS