Open In App

How to check whether an array is subset of another array using JavaScript ?

Last Updated : 13 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads