DEV Community

김영민
김영민

Posted on

Mastering Map and Set in JavaScript

Introduction to Map and Set in JavaScript

Map and Set are new data structures introduced in ES6 to complement the existing objects and arrays, providing more powerful features and flexibility in specific situations.

Map: A More Powerful Key-Value Store

Map is a data structure that stores key-value pairs, offering more robust features and flexibility compared to traditional objects.

Key Features of Map

  • No key restrictions: Unlike objects, where keys are limited to strings and symbols, Map allows any type to be used as a key.
  • Preserves insertion order: Map remembers the order in which elements were inserted, making it an iterable object.
  • Easy size checking: Map has a size property, making it simple to check the number of elements.
  • Performance optimization: Map provides more efficient addition, deletion, and lookup of key-value pairs compared to objects.

Using Map

const map = new Map();

// Add elements
map.set('key1', 'value1');
map.set(42, 'value2'); // Using a number as a key
map.set({ a: 1 }, 'value3'); // Using an object as a key

console.log(map.get('key1')); // 'value1'
console.log(map.get(42)); // 'value2'

// Check size
console.log(map.size); // 3

// Delete an element
map.delete(42);

// Check if a key exists
console.log(map.has(42)); // false

// Iterate over all elements
map.forEach((value, key) => {
  console.log(key, value);
});
Enter fullscreen mode Exit fullscreen mode

Set: A Collection of Unique Values

Set is a data structure that stores a collection of unique values, similar to an array but without duplicates.

Key Features of Set

  • No duplicates: Set automatically removes duplicates, ensuring all values are unique.
  • Stores unique values: Set can store numbers, strings, objects, and other values, with each value being unique.
  • Preserves insertion order: Set remembers the order in which elements were inserted.

Using Set

const set = new Set();

// Add elements
set.add(1);
set.add(2);
set.add(2); // Duplicate value is ignored
set.add('Hello');

console.log(set); // Set { 1, 2, 'Hello' }

// Check size
console.log(set.size); // 3

// Delete an element
set.delete(1);

// Check if a value exists
console.log(set.has(1)); // false

// Iterate over all elements
set.forEach(value => {
  console.log(value);
});
Enter fullscreen mode Exit fullscreen mode

Practical Use Case: Removing Duplicates from an Array

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

Conclusion

In conclusion, Map and Set are powerful data structures in JavaScript that provide more flexibility and features compared to traditional objects and arrays. By understanding how to use Map and Set, you can write more efficient and effective code, and take advantage of their unique features to solve complex problems.

Top comments (0)