JavaScript Set union()
Syntax & Examples

Set.union() method

The union() method of the Set object in JavaScript takes another set as an argument and returns a new set containing elements which are in either or both the original set and the given set.


Syntax of Set.union()

The syntax of Set.union() method is:

union(other)

This union() method of Set takes a set and returns a new set containing elements which are in either or both of this set and the given set.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe set to combine with the original set.

Return Type

Set.union() returns value of type Set.



✐ Examples

1 Using union() to combine two sets of numbers

In JavaScript, we can use the union() method to combine two sets of numbers.

For example,

  1. Create a new Set object setA with initial values 1, 2, and 3.
  2. Create another Set object setB with initial values 3, 4, and 5.
  3. Use the union() method to combine setA and setB, storing the result in unionSet.
  4. Log the unionSet to the console using console.log().

JavaScript Program

const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);
const unionSet = setA.union(setB);
console.log(unionSet);

Output

Set { 1, 2, 3, 4, 5 }

2 Using union() with sets of strings

In JavaScript, we can use the union() method to combine two sets of strings.

For example,

  1. Create a new Set object setA with initial values 'apple', 'banana', and 'cherry'.
  2. Create another Set object setB with initial values 'banana', 'cherry', and 'date'.
  3. Use the union() method to combine setA and setB, storing the result in unionSet.
  4. Log the unionSet to the console using console.log().

JavaScript Program

const setA = new Set(['apple', 'banana', 'cherry']);
const setB = new Set(['banana', 'cherry', 'date']);
const unionSet = setA.union(setB);
console.log(unionSet);

Output

Set { 'apple', 'banana', 'cherry', 'date' }

3 Using union() to combine sets of objects

In JavaScript, we can use the union() method to combine two sets of objects.

For example,

  1. Create a new Set object setA with initial objects representing different people.
  2. Create another Set object setB with some overlapping objects.
  3. Use the union() method to combine setA and setB, storing the result in unionSet.
  4. Log the unionSet to the console using console.log().

JavaScript Program

const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const person3 = { name: 'Doe' };
const setA = new Set([person1, person2]);
const setB = new Set([person2, person3]);
const unionSet = setA.union(setB);
console.log(unionSet);

Output

Set { { name: 'John' }, { name: 'Jane' }, { name: 'Doe' } }

Summary

In this JavaScript tutorial, we learned about union() method of Set: the syntax and few working examples with output and detailed explanation for each example.