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 id="Using-the-i-for-loop-and-includes-method-i-to-determine-if-one-array-is-a-subset-of-another-array">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 id="Using-the-i-array-every-method-and-set-i-to-check-if-one-array-is-a-subset-of-another-array">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!

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

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.


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

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.