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:
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
let arr1 = [ "GFG" , "Geeks" , "Portal" ,
"Geek" , "GFG_1" , "GFG_2" ];
let arr2 = [ "GFG" , "Geeks" , "Geek" ];
function GFG_Fun() {
let res = arr2.every( function (val) {
return arr1.indexOf(val) >= 0;
});
let not = "" ;
if (!res) {
not = "not" ;
}
console.log( "Array_2 is " + not
+ " the subset of Array_1" );
}
GFG_Fun();
|
Output
Array_2 is the subset of Array_1
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
let arr1 = [ "GFG" , "Geeks" , "Portal" ,
"Geek" , "GFG_1" , "GFG_2" ];
let arr2 = [ "GFG" , "Geeks" , "GeekForGeeks" ];
function GFG_Fun() {
let res = !arr2.some(val => arr1.indexOf(val) === -1);
let not = "" ;
if (!res) {
not = "not" ;
}
console.log( "Array_2 is " + not
+ " the subset of Array_1" );
}
GFG_Fun();
|
Output
Array_2 is not the subset of Array_1
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
13 Jul, 2023
Like Article
Save Article