DEV Community

Cover image for Real-world usage of Map and Set data types of JavaScript
Rahul Raveendran
Rahul Raveendran

Posted on

Real-world usage of Map and Set data types of JavaScript

If you are a JavaScript developer, you may have come across the Map and Set data types. When I first learned about these concepts, I had no idea how they would help me with real-world projects. But don't worry, I will share some examples of how I have used the concepts of Map and Set in my own projects.

If you don't know about the concept read here

1. Removing duplicates from an array

Set data type won't allow duplicate values, so creating a new set from the array will give us an array with unique values.

const array = [1, 1, 2, 3, 4, 5, 5];
const uniqueValuesArray = new Set(array);
console.log([...uniqueValuesArray ]); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2. Storing and retrieving key-value pairs

Maps are useful for storing and retrieving key-value pairs in JavaScript. This makes them ideal for building data structures and managing data in applications.

const userMap = new Map();
userMap.set('John', { age: 25, location: 'New York' });
userMap.set('Jane', { age: 30, location: 'Los Angeles' });
console.log(userMap.get('John')); // { age: 25, location: 'New York' }
Enter fullscreen mode Exit fullscreen mode

3. Efficient lookup

Sets and Maps can be used for efficient lookups. For example, if you have a large dataset and you need to check if a value exists in it or not, a Set would be more efficient than looping through the entire dataset to find the value.

const values = new Set([1, 2, 3, 4, 5]);
console.log(values.has(3)); // true
console.log(values.has(6)); // false
Enter fullscreen mode Exit fullscreen mode

4. Counting occurrences

Sets can be used for counting the occurrences of values in an array.

const fruitArray = ['apple', 'banana', 'orange', 'apple', 'orange', 'orange'];
const fruitCount = new Map();
fruitArray.forEach((fruit) => {
  if (fruitCount.has(fruit)) {
    fruitCount.set(fruit, fruitCount.get(fruit) + 1);
  } else {
    fruitCount.set(fruit, 1);
  }
});
console.log(fruitCount); // Map(3) { 'apple' => 2, 'banana' => 1, 'orange' => 3 }
Enter fullscreen mode Exit fullscreen mode

These are some examples you can use in your projects.

Top comments (0)