search
HomeWeb Front-endJS TutorialHow to calculate the union of JavaScript arrays?

如何计算 JavaScript 数组的并集?

We can get the union of two arrays by merging the two arrays and removing duplicate elements, and the union gives the unique elements in both arrays.

In this tutorial, we will learn to calculate the union of JavaScript arrays using various methods.

Use set() data structure

The first method is to use the set() data structure. Collection data structures can only contain unique elements. We can add all the elements of both arrays to the set and create a new array from the elements of the set to create the union.

grammar

Users can use the set data structure to calculate the union of JavaScript arrays according to the following syntax.

let union = [...new Set([...array1, ...array2])];

In the above syntax, we use the spread operator to concatenate two arrays and create a new collection from the resulting array. After that, we use the spread operator again to add the elements of the collection to the array.

Example 1

In the example below, array1 and array2 contain some common numbers. First, we connect array1 and array2 using the spread operator. After that, we create a set from the resulting array using the new Set() constructor. The set can only contain unique elements. Therefore, it contains all elements in the union of the two arrays.

After that, we use the spread operator to add all the elements of the collection to the associative array. In the output, the user can observe the union of the two arrays.

<html>
<body>
   <h3 id="Using-the-i-set-i-data-structure-to-compute-the-union-of-two-arrays-in-JavaScript"> Using the <i> set() </i> data structure to compute the union of two arrays in JavaScript </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      
      // using the set() to compute union
      let array1 = [1, 2, 3, 4, 5];
      let array2 = [4, 5, 6, 7, 8];
      let union = [...new Set([...array1, ...array2])];
      output.innerHTML = "The first array is " + array1 + "<br>";
      output.innerHTML += "The second array is " + array2 + "<br>";
      output.innerHTML += "The union of the two arrays is " + union + "<br>";
   </script>
</body>
</html>

Using objects to calculate the union of JavaScript arrays

In this method, we can add array values ​​as object properties. The object always contains unique keys. So we can use the array element as the key of the object and any value for that particular key. After that we can get all object keys to get the union of the arrays.

grammar

Users can use objects to calculate the union of arrays according to the following syntax.

for () {
   union[names1[i]] = 1;
}
for (let key in the union) {
   finalArray.push(key);
}

In the above syntax, first, we push all the array elements as keys of the object. After that we get the keys from the object and add them to the array.

Example 2

In the example below, we have two arrays named names1 and names2. We add the first array element as the object's key. After that, we add the elements of the second array as keys to the object.

Next, we loop through the object, get the object's key and push it to the FinalArray. FinalArray contains the union of the Name1 and Name2 arrays.

<html>
<body>
   <h3 id="Using-the-i-object-i-to-compute-the-union-of-two-arrays-in-JavaScript"> Using the <i> object </i> to compute the union of two arrays in JavaScript </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      
      // using the object to compute the union of two arrays
      let names1 = ["John", "Peter", "Sally", "Jane", "Mark"];
      let names2 = ["Peter", "Sally", "Greg"];
      let union = {};
      
      //Add all the elements of the first array to the object
      for (let i = 0; i < names1.length; i++) {
         union[names1[i]] = 1;
      }
      for (let i = 0; i < names2.length; i++) {
         union[names2[i]] = 1;
      }
      
      //Convert the object to an array
      let finalArray = [];
      for (let key in union) {
         finalArray.push(key);
      }
      output.innerHTML = "First array: " + JSON.stringify(names1) + "<br>";
      output.innerHTML += "Second array: " + JSON.stringify(names2) + "<br>";
      output.innerHTML += "The union of the two arrays: " + JSON.stringify(finalArray) + "<br>";
   </script>
</body>
</html>

Use Filter() and Concat() methods

concat() method is used to merge two or more arrays. We can use the filter() method to merge two arrays and filter the unique elements. This way, we can use the concat() and filter() methods to calculate the union of arrays.

grammar

Users can use the filter() and concat() methods to calculate the union of arrays according to the following syntax.

let cities = cities1.concat(cities2);
cities.sort();
let unionCities = cities.filter((value, index) => cities.indexOf(value) === index);

In the above syntax, we first merge the two arrays, sort them, and then use the filter() method to filter the unique elements.

Example 3

In the example below, the city1 and citites2 arrays contain some city names, some of which are common. The cities array contains the array elements of both arrays.

After that, we use the sort() method to sort the city array. Next, we use the filter() method to filter unique values ​​from the cities array. In the filter() method, we pass the callback function as parameter, which checks if the index of the current city is equal to the current index to remove duplicate elements.

<html>
<body>
   <h3 id="Using-the-i-filter-and-concat-methods-i-to-compute-the-union-of-two-arrays-in-JavaScript"> Using the <i> filter() and concat() methods </i> to compute the union of two arrays in JavaScript </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let cities1 = ["Surat", "Ahmedabad", "Rajkot", "Vadodara", "Pune"];
      let cities2 = ["Mumbai", "Pune", "Nagpur", "Nashik", "Rajkot"];
      let cities = cities1.concat(cities2);
      cities.sort();
      
      // filter unique values in the array
      let unionCities = cities.filter((value, index) => cities.indexOf(value) === index);
      output.innerHTML = "First array: " + JSON.stringify(cities1) + "<br>";
      output.innerHTML += "Second array: " + JSON.stringify(cities2) + "<br>";
      output.innerHTML += "The union of the two arrays: " + JSON.stringify(unionCities) + "<br>";
   </script>
</body>
</html>

Conclusion

The user learned three different ways to calculate the union of arrays in JavaScript. The first approach requires linear code using a collection data structure. The second method uses objects and the third method uses filter() and concat() methods.

The above is the detailed content of How to calculate the union of JavaScript arrays?. 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 Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.