new Map() or new Set() ?

Tay Bencardino
3 min readJan 30, 2024

--

Recently, I’ve been working on a task where I have to use both of them. I’ve never used this before; it was a great lesson.

Photo by Burst on Unsplash

What is a Map?

A Map is a built-in data structure in TypeScript (and JavaScript) that allows you to store key-value pairs. Each key can be of any data type, and the keys are unique within a Map.

✨ Use Map when you need to associate values with unique keys and you want to maintain the order of insertion.

// Creating a Map
let myMap = new Map();

// Adding key-value pairs
myMap.set('name', 'John');
myMap.set('age', 25);

// Retrieving values
console.log(myMap.get('name')); // Output: John
console.log(myMap.get('age')); // Output: 25

// Checking if a key exists
console.log(myMap.has('name')); // Output: true

// Deleting a key-value pair
myMap.delete('age');

Why use Map instead of an Object?

  • Key Types: In a Map, keys can be of any data type, including objects or functions. In contrast, object keys are always converted to strings.
let myMap = new Map();
let myObject = {};

myMap.set({ key: 'obj' }, 'Value for Object Key');
myObject[{ key: 'obj' }] = 'Value for Object Key';

console.log(myMap.get({ key: 'obj' })); // Output: undefined (because a new object is used)
console.log(myObject[{ key: 'obj' }]); // Output: Value for Object Key
  • Iteration Order: The order of elements in a Map is guaranteed to be the order in which they were inserted. This is not guaranteed with regular objects.
let myMap = new Map();
let myObject = {};

myMap.set('a', 1);
myMap.set('b', 2);

myObject['a'] = 1;
myObject['b'] = 2;

console.log([...myMap.keys()]); // Output: ['a', 'b']
console.log(Object.keys(myObject)); // Output: ['a', 'b'] or ['b', 'a'] (order not guaranteed)

What is a Set?

A Set is another built-in data structure that stores unique values, similar to a list, but without duplicates. It's great for maintaining a collection of distinct elements.

// Creating a Set
const mySet = new Set();

// Adding elements
mySet.add('apple');
mySet.add('banana');
mySet.add('apple'); // Duplicates are ignored

// Checking if an element exists
console.log(mySet.has('banana')); // Output: true

// Deleting an element
mySet.delete('apple');

Set vs. Array:

Why use Set instead of an Array?

  • Uniqueness: A Set automatically ensures that all elements are unique, whereas in an array, you must manually check for duplicates.
  • No Key-Value Pair: Unlike Map, Set does not store key-value pairs; it only stores individual values.
  • Ordering: The order of elements in a Set is based on the order of insertion, but it is not as emphasized as in a Map.
  • Useful Methods: Besides the ones mentioned, Set provides methods like clear() to remove all elements and forEach() for iteration.

Use cases:

// REMOVING DUPLICATES FROM ARRAYS

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueValues = new Set(arrayWithDuplicates);
const arrayWithoutDuplicates = Array.from(uniqueValues);

console.log(arrayWithoutDuplicates) // Output: [1,2,3,4,5]
// CHECKING FOR UNIQUENESS

const uniqueEmails = new Set(['user@example.com', 'user2@example.com']);
if (!uniqueEmails.has('newuser@example.com')) {
// Add the new email to the set
uniqueEmails.add('newuser@example.com');
}

✨ Use Set when you need to maintain a collection of unique values, the insertion order is less critical.

In summary, Map and Set provide more flexibility and specialised behaviour than objects and arrays in certain scenarios. They are particularly useful when you need unique keys, guaranteed iteration order, or automatic handling of duplicates.

ASet It is a handy data structure when dealing with collections of unique values and provides methods for common set operations.

  • Use Set when you need to store a collection of unique values without associating them with specific keys.
  • Use Map when you need to associate values with unique keys in a key-value pair fashion.

In general, if you only need to maintain a set of unique values, Set is more appropriate. If you need to associate values with specific keys or if you require a specific order of elements, then Map is the better choice.

--

--