


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
