


How to check if an array is a subset of another array using JavaScript?
The first array is a subset of the second array if the second array contains all elements of the first array. So sometimes we may need to check if one array is a subset of another array.
In this tutorial, we will learn to use three different methods to check if an array is a subset of another array.
Use for loop and array.includes() method
Users can use a for loop to iterate each element of the first array. Afterwards, they can use the includes() method to check if the second array contains every element of the first array.
The first array is a subset of the second array if the second array contains all elements of the first array.
grammar
Users can use the for loop and the includes() method according to the following syntax to determine whether an array is a subset of another array.
for (let ele of array1) { if (!array2.includes(ele)) { return false; } }
In the above syntax, we check whether array1 is a subset of array2.
algorithm
Step 1 - We will check if array1 is a subset of array2.
Step 2 - Use for-of to loop through each element of the array.
Step 3 - Use the array.includes() method to check whether each element of array1 is included in array2.
Step 4 - Return false if any single element in array1 is not contained in array2.
< /里>Step 5 - If array2 contains all elements of array1, the for-loop iteration will succeed and return true .
Example
We created three arrays containing different values in the example below. We created the isSubset() function which accepts two arrays as parameters. This function checks whether array1 is a subset of array2 and returns a Boolean value based on that result.
We are checking if array2 and array3 are subsets of array1. The user can observe the results in the output.
<html> <body> <h3>Using the <i>for loop and includes() method</i> to determine if one array is a subset of another array.</h3> <p id = "output"> </p> <script> let output = document.getElementById("output"); let array1 = [10, 20, 30, 40, 50, 60, 70, 80, 90]; let array2 = [20, 30, 70, 80]; let array3 = [20, 43, 45]; function isSubset(array1, array2) { // Iterating through all the elements of array1 for (let ele of array1) { // check if array2 contains the element of array1 if (!array2.includes(ele)) { output.innerHTML += "The " + array1 + " is not a subset of " + array2 + "<br>"; return false; } } output.innerHTML += "The " + array1 + " is a subset of " + array2 + "<br>"; // If array1 contains all elements of array2 return true return true; } isSubset(array2, array1); isSubset(array3, array1) </script> </body> </html>
Use array.some() and array.indexOf() methods
Thearray.some() method takes a callback function as parameter, which returns a Boolean value based on at least one element of the reference array that meets the condition.
array.indexOf() method returns the index of the element if the element exists in the array; otherwise, -1 is returned. So if we find that any element in the first array has index -1 in the second array, it means that the first array is not a subset of the second array.
grammar
Users can use the array.some() and array.indexOf() methods according to the following syntax to check whether an array is a subset of another array.
let isSubset = !data2.some((string) => data1.indexOf(string) == -1);
In the above syntax, if the some() method returns true, the data1 array is not a subset of data2. Therefore, we store its opposite boolean value in the isSubset variable.
Example
The following example contains two string arrays and checks whether the data1 array is a subset of the data2 array. The data1 array contains all elements of data2. Therefore, the user can see in the output that the data2 array is a subset of data1.
Using the array.some() and array.indexOf() method to check if one array is a subset of another.
<script> let output = document.getElementById("output"); let data1 = ["Hello", "Hi", "Users"]; let data2 = ["Hello", "Users"]; let isSubset = !data2.some((string) => data1.indexOf(string) == -1); if (isSubset) { output.innerHTML += "The " + data2 + " is a subset of " + data1 + " array. <br>"; } else { output.innerHTML += "The " + data2 + " is not a subset of " + data1 + " array. <br>"; } </script>
Use array.every() method and set()
The array.every() method will return true if each element meets the conditions returned by the callback function.
We can create a set() of all array elements because the set contains unique array elements.
grammar
Use the set and every() methods according to the syntax below.
let setOfArray = new Set(num1); let result = num2.every(num => setOfArray.has(num));
Example
In the following example, we create a collection of all elements of the num1 array. After that, we use the has() method of javascript set to check whether the set contains each element of the num2 array.
<html> <body> <h3>Using the <i>array.every() method and set</i> to check if one array is a subset of another array.</h3> <p id="output"></p> <button onclick="checkForSubset()">Check for subset</button> <script> let output = document.getElementById("output"); let num1 = [45, 65, 45, true, false, 45, 43, 32]; let num2 = [false, true, false, true]; function checkForSubset() { // create a set of the parent array let setOfArray = new Set(num1); // Check if every element of the child array is in the set of the parent array let result = num2.every(num => setOfArray.has(num)); if (result) { output.innerHTML += "The " + num2 + " is a subset of " + num1 + " array. <br>"; } else { output.innerHTML += "The " + num2 + " is not a subset of " + num1 + " array. <br>"; } } </script> </body> </html>
The above is the detailed content of How to check if an array is a subset of another array using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c
