Wednesday, January 22, 2025
HomeProgrammingTypeScript Set

TypeScript Set

TypeScript, a superset of JavaScript, brings in additional features that make it easier to manage complex applications. One of the important features of TypeScript (and JavaScript) is the Set data structure. Sets allow you to store unique values of any type, whether primitive values or object references, and they can be very useful in a variety of scenarios like eliminating duplicates, efficient lookups, and more.

In this blog post, we’ll dive deep into TypeScript Set, exploring how it works, how to use it, and some practical examples.

What is a Set in TypeScript?

A Set is a collection of values where each value must be unique. A Set can store any type of data, such as numbers, strings, or even objects. The key feature of a Set is that it does not allow duplicate values. If you try to add a duplicate value, it will simply be ignored.

The Set object is part of the ES6 (ECMAScript 2015) standard, and TypeScript supports it out of the box. It provides an easy way to store distinct elements and perform various operations like adding, deleting, or checking for existence of elements in a collection.

Creating a Set in TypeScript

To create a Set, we use the Set constructor. You can initialize a Set with an array or create an empty Set and add elements later.

Creating an Empty Set:

let mySet = new Set();

Creating a Set with Initial Values:

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

In this example, the Set is initialized with values 1, 2, 3, 4, and 5. These values are automatically converted into unique values, ensuring that no duplicates are stored.

See also  Unit Testing

Basic Operations on Sets

Once you have a Set, there are several key operations you can perform, such as adding, deleting, checking existence, and iterating over the Set. Let’s look at each operation in detail.

1. Adding Elements to a Set

To add an element to a Set, use the add() method. If the value already exists in the Set, it will not be added again.

let mySet = new Set();
mySet.add(1);   // Set { 1 }
mySet.add(2);   // Set { 1, 2 }
mySet.add(2);   // Set { 1, 2 } (Duplicate, won't be added)
console.log(mySet); // Output: Set { 1, 2 }

2. Checking for an Element

To check if an element exists in a Set, you can use the has() method, which returns a boolean value (true or false).

let mySet = new Set([1, 2, 3]);
console.log(mySet.has(2));  // Output: true
console.log(mySet.has(4));  // Output: false

3. Deleting Elements from a Set

To remove an element from a Set, you can use the delete() method. It will remove the specified value if it exists in the Set and return true. If the value doesn’t exist, it returns false.

let mySet = new Set([1, 2, 3, 4]);
mySet.delete(3);  // Set { 1, 2, 4 }
console.log(mySet);  // Output: Set { 1, 2, 4 }

4. Getting the Size of a Set

You can check how many elements are in a Set using the size property.

let mySet = new Set([1, 2, 3, 4]);
console.log(mySet.size);  // Output: 4

5. Clearing All Elements from a Set

To remove all elements from a Set, you can use the clear() method.

let mySet = new Set([1, 2, 3]);
mySet.clear();
console.log(mySet);  // Output: Set {}

Iterating Over a Set

You can iterate over the values of a Set using either the forEach() method or a for...of loop.

See also  Bubble sort Algorithm

Using forEach() Method:

let mySet = new Set([1, 2, 3, 4]);
mySet.forEach(value => {
  console.log(value);
});
// Output:
// 1
// 2
// 3
// 4

Using for...of Loop:

let mySet = new Set([1, 2, 3, 4]);
for (let value of mySet) {
  console.log(value);
}
// Output:
// 1
// 2
// 3
// 4

Set vs Array: When to Use a Set?

While both arrays and sets are used to store collections of data, there are some key differences that make each of them suitable for different use cases.

  • Uniqueness: Sets automatically enforce uniqueness. If you try to add duplicate values, they are ignored. Arrays allow duplicates.
  • Performance: Sets offer more efficient checks for existence (using has()) compared to arrays (which require indexOf() or includes()).
  • Order: Both Sets and Arrays maintain the insertion order of elements.

When to Use Set:

  • When you need to ensure uniqueness of values and don’t care about order.
  • When performing frequent lookups and you need to check if an item is present in the collection.

When to Use Array:

  • When you need to maintain duplicates or when order is crucial (such as indexing or slicing).
  • When you need to perform more complex operations like sorting or filtering elements.

Common Use Cases for Sets in TypeScript

  • Removing Duplicates: If you have an array with duplicate values, converting it into a Set automatically removes duplicates.
let numbers = [1, 2, 3, 1, 2, 3];
let uniqueNumbers = new Set(numbers);
console.log(uniqueNumbers); // Output: Set { 1, 2, 3 }
  • Efficient Lookup Operations: If you need to frequently check if an item exists, a Set is more efficient than an array, especially when dealing with large collections.
let mySet = new Set([1, 2, 3, 4, 5]);
console.log(mySet.has(3));  // Output: true
console.log(mySet.has(6));  // Output: false
  • Tracking Items: Use a Set to track items in a game, event listeners, or any scenario where you need to track unique entities.
See also  Is JavaScript Object-Oriented?

Conclusion

The Set data structure in TypeScript is an incredibly useful tool when working with unique collections of data. With its easy-to-use API, Set provides an efficient way to handle operations like checking for existence, eliminating duplicates, and performing lookups. It also offers performance advantages when compared to arrays in specific scenarios, such as membership testing.

By understanding how to use Sets and their features in TypeScript, you can make your applications more efficient, cleaner, and more effective at handling collections of unique values. Whether you’re working with numbers, strings, or objects, the Set data structure is an excellent addition to your TypeScript toolkit.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x