How to create a set in TypeScript

In TypeScript, sets are not about organizing chairs on a stage. They're data structures built for one purpose: holding unique elements without duplicates.

Building a Basic Set

const fruits = new Set(["apple", "banana", "orange", "apple"]); console.log(fruits.size); // Outputs: 3 (Duplicates are ignored) fruits.add("grapefruit"); for (const fruit of fruits) { console.log(fruit); // Prints "apple", "banana", "orange", "grapefruit" } fruits.delete("apple"); console.log(fruits.has("apple")); // Outputs: false

This example showcases creating a set with the Set constructor, adding elements, checking size, iterating using for-of, and removing elements. Notice how "apple" appears only once even though it's added twice.

Practical Applications of Sets

  1. Finding unique values: Analyze large datasets to identify unique elements, like the number of unique visitors to a website or distinct words in a document.
  2. Removing duplicates: Clean redundant data in lists or arrays, ensuring unique entries for efficient processing.
  3. Set operations: Perform mathematical operations like union, intersection, and difference between sets to discover relationships and patterns within data.

Iterating over Sets

Sets can be easily iterated using loops or built-in methods.

let colors = new Set<string>(); colors.add("red"); colors.add("green"); colors.add("blue"); // Iterating using forEach colors.forEach(color => console.log(color)); // Iterating using for...of loop for (const color of colors) { console.log(color); }

The forEach method and for...of loop are used to iterate over the values in the Set.

Using Sets for Array Deduplication

Sets are handy for deduplicating arrays, as they automatically discard duplicate values.

let numbers = [1, 2, 3, 4, 2, 3, 5]; let uniqueNumbers = new Set(numbers); let deduplicatedArray = Array.from(uniqueNumbers); console.log(deduplicatedArray); // Outputs: [1, 2, 3, 4, 5]

In this example, a Set is used to deduplicate an array of numbers, and then the Array.from method is used to convert the Set back into an array.

Sets with Objects

Sets can store objects, and uniqueness is determined by object reference.

let personSet = new Set<{ name: string, age: number }>(); personSet.add({ name: "Alice", age: 30 }); personSet.add({ name: "Bob", age: 25 }); personSet.add({ name: "Alice", age: 30 }); // Different object, so it's added console.log(personSet.size); // Outputs: 3

In this case, even though two objects have the same properties, they are considered unique because they are different object references.

Set Methods and Chaining

const availableColors = new Set(["red", "blue", "green"]); const chosenColors = new Set(["blue", "purple", "yellow"]); const combinedColors = availableColors.union(chosenColors); // Combines sets without duplicates const sharedColors = availableColors.intersection(chosenColors); // Finds elements present in both sets console.log(combinedColors.size); // Outputs: 5 (Unique elements from both sets) console.log(sharedColors.has("blue")); // Outputs: true availableColors.add("purple").delete("green"); // Chaining methods for adding and removing elements

This example demonstrates using various set methods like union, intersection, and chaining add and delete for conciseness. These operations unlock powerful data analysis and manipulation possibilities.

Beyond Basic Sets

  1. TypeScript allows defining custom equality checking for elements within sets using the equals function, making sets suitable for complex data types.
  2. Sets can be used to implement efficient membership checks, making them ideal for situations where finding if an element belongs to a specific collection is crucial.

Points to Remember

  1. Sets are unordered, so element order during iteration is unpredictable.
  2. They're optimized for unique elements, making them inefficient for storing duplicates.
  3. Choose sets over other data structures like arrays when uniqueness and efficient membership checks are crucial for your needs.

Conclusion

Sets in TypeScript provide a straightforward and efficient way to manage collections of unique values. They are particularly useful for scenarios where uniqueness and simplicity in value management are critical. TypeScript's type system enhances the safety and expressiveness of working with Sets.