Introduction to Sets and Maps in JavaScript

Sets and maps are data structures in JavaScript that allow you to store and manipulate collections of data. In this article, we’ll explore the basics of sets and maps, and some common use cases for each.

Using Sets in TypeScript

A set is a collection of unique values. In TypeScript, you can create a set using the Set class. Here is an example:

const mySet = new Set<number>();

mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(1); // Duplicate value is ignored

console.log(mySet.has(1)); // Output: true
console.log(mySet.size); // Output: 3

mySet.delete(2);

console.log(mySet.size); // Output: 2

mySet.clear();

console.log(mySet.size); // Output: 0

In this example, we create a set of numbers using the Set class. We add four values to the set, but the duplicate value is ignored because sets only store unique values. We then use the has method to check if the set contains a value, the size property to get the number of values in the set, the delete method to remove a value from the set, and the clear method to remove all values from the set.

Common Use Cases for Sets

One common use case for sets is to remove duplicates from an array:

const myArray = [1, 2, 2, 3, 3, 3];
const mySet = new Set(myArray);
const uniqueArray = Array.from(mySet);

console.log(uniqueArray); // Output: [1, 2, 3]

In this example, we create a set from an array using the Set constructor, which automatically removes duplicates. We then convert the set back to an array using the Array.from method.

Another common use case for sets is to perform set operations such as union, intersection, and difference:

const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);

const union = new Set([...setA, ...setB]);
const intersection = new Set([...setA].filter(x => setB.has(x)));
const difference = new Set([...setA].filter(x => !setB.has(x)));

console.log(union); // Output: Set(4) {1, 2, 3, 4}
console.log(intersection); // Output: Set(2) {2, 3}
console.log(difference); // Output: Set(1) {1}

In this example, we create two sets and perform set operations on them using various methods such as the spread operator and the filter method.

Using Maps in TypeScript

A map is a collection of key-value pairs. In TypeScript, you can create a map using the Map class. Here is an example:

const myMap = new Map<string, number>();

myMap.set('one', 1);
myMap.set('two', 2);
myMap.set('three', 3);

console.log(myMap.get('two')); // Output: 2
console.log(myMap.has('four')); // Output: false
console.log(myMap.size); // Output: 3

myMap.delete('three');

console.log(myMap.size); // Output: 2

myMap.clear();

console.log(myMap.size); // Output: 0

In this example, we create a map of strings and numbers using the Map class. We add three key-value pairs to the map