Table of Contents
Use set() data structure
grammar
Example 3
Using objects to calculate the union of JavaScript arrays
Use Filter() and Concat() methods
Conclusion
Home Web Front-end JS Tutorial How to calculate the union of JavaScript arrays?

How to calculate the union of JavaScript arrays?

Sep 10, 2023 pm 06:49 PM

如何计算 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])];
Copy after login

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> 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>
Copy after login

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);
}
Copy after login

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> 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>
Copy after login

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);
Copy after login

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> 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>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

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

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

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

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

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

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

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

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

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 Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

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

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

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

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

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

See all articles