.union()

The method of combining two collections, which returns a new collection with elements that appear in either or both collections.

Time to read: less than 5 min

Briefly

The union() method combines the current collection with another and returns a new one consisting of elements found in either collection.

In mathematics, this is called the union of two sets. It is described as follows: the union of sets A and B is the set that consists of elements found in either set A or B.

This can be expressed with the formula:

A ∪ B = { x | x ∈ A ∨ x ∈ B }
Union of two sets

Example

In the last two projects, engineer Fyodor used a specific tech stack. When compiling his CV, Fyodor decides to list the skills he now possesses. He needs to compare two collections and get a list of technologies used in at least one of the projects. The union() method will help Fyodor with this:

        
          
          const project1 = new Set(['PHP', 'Bash', 'Docker', 'JavaScript', 'CSS'])const project2 = new Set(['Docker', 'JavaScript', 'Bash', 'Postgres', 'MongoDB'])const result = project1.union(project2)console.log(result)// Set(9) {//   'PHP',//   'Bash',//   'Docker',//   'JavaScript',//   'CSS',//   'Postgres',//   'MongoDB'// }
          const project1 = new Set(['PHP', 'Bash', 'Docker', 'JavaScript', 'CSS'])
const project2 = new Set(['Docker', 'JavaScript', 'Bash', 'Postgres', 'MongoDB'])

const result = project1.union(project2)

console.log(result)
// Set(9) {
//   'PHP',
//   'Bash',
//   'Docker',
//   'JavaScript',
//   'CSS',
//   'Postgres',
//   'MongoDB'
// }


        
        
          
        
      

How to write

The union() method takes one mandatory argument — an object containing the collection to be combined. If the argument is not provided, a TypeError exception will be thrown.

The argument can be either a Set object or a Set-like object, such as a Map.

💡 A Set-like object must have a size property and has() and keys() methods. A regular array, as well as a WeakSet object, are not considered Set-like objects, as they do not possess all the required properties and methods.

The union() method returns a new Set object containing the union of the original and specified collections. The order of elements will match the order of the original followed by the specified collection.

How to understand

The union() method allows combining two collections of elements without the need to write additional traversal and comparison code.

Support for the union() method in major browsers and in Node.js appeared in 2024. If you try to use the method in earlier versions, it will result in an error.

Поддержка в браузерах:
  • Chrome 122, поддерживается
  • Edge 122, поддерживается
  • Firefox 127, поддерживается
  • Safari 17, поддерживается
О Baseline