search
HomeWeb Front-endJS TutorialHow to check if an array is a subset of another array using JavaScript?

如何使用 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 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

The

array.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) =&gt; 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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

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