Set and Map are two amazing features JavaScript offers for handling data collection. Although at first they seem a bit scary, after you get the hang of them, they are very helpful for maintaining clean and efficient codes. Let's see how you may use them for your tasks.

What is a JavaScript Set?

A Set is like a special list where each item is unique. Sets will seem like a blessing if you have ever needed to ensure an array has no duplicates.

Essential Features of Sets

  • Unique Values: no duplicates allowed.
  • Things remain in the order that you add them in.
  • Flexible Data Types: numbers, strings, objects; they all work.

How to Create a Set in JavaScript

Here’s how to make a Set:

const mySet = new Set();

You can also start with some values:

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

Adding and Removing Values in a Set

  • Add something:

    mySet.add(5);
    console.log(mySet); // Output: Set(5) { 1, 2, 3, 4, 5 }
  • Remove something:

    mySet.delete(3);
    console.log(mySet); // Output: Set(4) { 1, 2, 4, 5 }
  • Check if it’s there:

    console.log(mySet.has(2)); // Output: true
    console.log(mySet.has(7)); // Output: false
  • Clear everything:

    mySet.clear();
    console.log(mySet); // Output: Set(0) {}

Converting Between Sets and Arrays

Convert a Set to an Array

Need an array instead? Easy:

const set = new Set([1, 2, 3]);
const array = [...set];
console.log(array); // Output: [1, 2, 3]

Convert an Array to a Set

This method removes the duplicates in an array:

const array = [1, 2, 2, 3, 4, 4];
const uniqueSet = new Set(array);
console.log(uniqueSet); // Output: Set(4) { 1, 2, 3, 4 }

What Is a Map in JavaScript?

A Map is similar to a detailed item. You can use nearly anything as a key instead of using simply strings like objects.

Key Features of Maps

  • Flexible Keys: Numbers, objects, functions; they all work.
  • Order Matters: Keeps entries in the order you add them.
  • Optimized: Fast lookups and updates.

How to Create a Map in JavaScript

Here’s how to make a Map:

const myMap = new Map();

Adding and Removing Key-Value Pairs in a Map

  • Add a key-value pair:

    myMap.set('name', 'Ahmed');
    myMap.set('age', 25);
    console.log(myMap); // Output: Map(2) { 'name' => 'Ahmed', 'age' => 25 }
  • Get a value by key:

    console.log(myMap.get('name')); // Output: Ahmed
  • Check if a key exists:

    console.log(myMap.has('age')); // Output: true
  • Remove a key:

    myMap.delete('age');
    console.log(myMap); // Output: Map(1) { 'name' => 'Ahmed' }
  • Clear everything:

    myMap.clear();
    console.log(myMap); // Output: Map(0) {}

Map vs Set: Key Differences

FeatureSetMap
StorageUnique valuesKey-value pairs
OrderKeeps orderKeeps order
Key TypesN/AAnything
Best ForUnique itemsKeyed data

When to Use Sets and Maps

  • Use a Set when:
    • You need to avoid/remove duplicates.
    • You’re working with unique collections, like a list of user IDs.
  • Use a Map when:
    • You need to link keys to values.
    • You’re working with dynamic or complex keys (like objects).

Real-World Examples

Removing Duplicates from an Array with a Set

const names = ['Ahmed', 'Sara', 'Ahmed', 'John'];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames); // Output: ['Ahmed', 'Sara', 'John']

Counting Word Occurrences with a Map

const text = 'hello world hello universe';
const wordCounts = new Map();

text.split(' ').forEach(word => {
  wordCounts.set(word, (wordCounts.get(word) || 0) + 1);
});

console.log(wordCounts);
// Output: Map(3) { 'hello' => 2, 'world' => 1, 'universe' => 1 }

FAQ

What’s the difference between a Set and an Array?

A Set automatically removes duplicates, while an Array doesn’t.

Can I use objects as keys in a Map?

Yes! Unlike objects, Maps allow any data type as a key.

How do I check the size of a Set or Map?

Use the .size property:

const set = new Set([1, 2, 3]);
console.log(set.size); // Output: 3

const map = new Map();
map.set('a', 1);
map.set('b', 2);
console.log(map.size); // Output: 2

With Sets and Maps in your toolbox, you can handle data more effectively in JavaScript. Give them a try and see how they simplify your coding!