ES6’s Map Collection Type
Methods & example of how to use Map with Big O breakdown
A Map is an object that holds key value pairs and remembers the original insertion order.
This is ES6’s ‘improved’ / alternative collection type; that picks up the slack where using an object was lacking.
Let’s look over Map’s set of built in methods to get started (# 1-9 link to it’s developer.mozilla.org documentation).
Map.prototype.clear()
Map.prototype.delete()
Map.prototype.entries()
Map.prototype.forEach()
Map.prototype.get()
Map.prototype.has()
Map.prototype.keys()
Map.prototype.set()
Map.prototype.values()
- new Map( ) creates a Map object
- Map.prototype.size
Some of these are likely familiar and function as you would image they do. Let’s take a moment to review a few of these helpful methods and their return types:
.delete( key )
deletes a specific element in Map object- return will be true ( if successful) or false (if element doesn’t exist)
.get( key )
returns the value when provided the key from Map object or undefined (if the key can’t be found)
.has( key )
returns true (if the key exists in the Map) or false (if key doesn’t exist in Map)
.set( key, value )
sets the value for the key in the Map. It returns the Map object itself . With this, you’re able to chain this method with other methods
.size
returns the number of elements in the given Map (or simply, the size)
There is much that can be done when using Map, these methods should be just enough to get started exploring the possibilities. I learned about Map more recently, while going through LeetCode’s discussion page on one of the most frequently asked interview questions- Two Sum.
**Take 20 minutes to try your hand at solving the algorithm with the link above- before I get into a solution using our new friend, Map**
Two Sum Ask:

Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Map Solution:

Time complexity breakdown:
O(n) for the iteration
O(1) for result.has( )
O(1) for result.get( )
O(1) for result.set( )
**Most Map operations, like set, get or has
, require a lookup. Similar to a Javascript object, lookup has O(1) time complexity**
So, we have solved Two Sum using a Map with O(n) or Linear time complexity as well as O(n) space complexity. We figure this space complexity because we are (potentially) storing each value with its index as a key => value pair in the Map.
If you have any questions, comments, corrections, etc. please leave your input below. I hope this article has been helpful in some way! Follow my journey on LinkedIn, and stay tuned for weekly blogs on my Medium page.