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 }

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 Type
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 Weak
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, поддерживается