Set

In JavaScript, a Set is a collection of unique values. Unlike an array, a Set does not allow duplicate elements. This makes it ideal for situations where you need to ensure that each element is only represented once.

Creating a Set

A Set can be created by passing an iterable (like an array) to the Set constructor.

Example:

javascript
	let numbers = new Set([1, 2, 3, 4, 5]);

Adding Elements to a Set

You can add elements to a Set using the add method. If you try to add a duplicate element, it will not be added to the Set.

Example:

javascript
	numbers.add(6);
	numbers.add(3); // This will not be added as 3 is already in the set

Accessing Set Elements

A Set does not provide direct access to its elements by index like an array. Instead, you can iterate over a Set or convert it into an array.

Removing Elements

Elements can be removed from a Set using the delete method. To remove all elements, use the clear method.

Example:

javascript
	numbers.delete(5); // Removes the element 5
	numbers.clear(); // Clears the set

Checking for Elements

You can check if an element is in a Set using the has method.

Example:

javascript
	if (numbers.has(2)) {
	  console.log('Set contains 2');
	} else {
	  console.log('Set does not contain 2');
	}

Iterating Over a Set

You can iterate over the elements of a Set using methods like forEach or the for...of loop.

Example:

javascript
	numbers.forEach(function (value) {
	  console.log(value);
	});
	
	for (let value of numbers) {
	  console.log(value);
	}

Size of a Set

The number of elements in a Set can be found using the size property.

Example:

javascript
	console.log(numbers.size); // Outputs the number of elements in the set

Use Cases for Set

  • Removing Duplicates: Quickly remove duplicates from an array.
  • Unique Collections: Maintain a collection of unique items, like IDs or keys.
  • Set Operations: Perform mathematical set operations like union, intersection, difference.

Conclusion

The Set object in JavaScript provides a powerful way to handle collections of unique values. Its functionality makes it ideal for situations where duplicates are not allowed, and each element needs to be unique.