Keyed Collections

This chapter introduces collections of data which are indexed by a key; Map and Set objects contain elements which are iterable in the order of insertion.

Maparrow-up-right is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

Methods and properties are:

For instance:

let map = new Map();

map.set('1', 'str1');   // a string key
map.set(1, 'num1');     // a numeric key
map.set(true, 'bool1'); // a boolean key

// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
alert( map.get(1)   ); // 'num1'
alert( map.get('1') ); // 'str1'

alert( map.size ); // 3

As we can see, unlike objects, keys are not converted to strings. Any type of key is possible.

map[key] isn’t the right way to use a Map

Although map[key] also works, e.g. we can set map[key] = 2, this is treating map as a plain JavaScript object, so it implies all corresponding limitations (only string/symbol keys and so on).

So we should use map methods: set, get and so on.

Map can also use objects as keys.

For instance:

Using objects as keys is one of the most notable and important Map features. The same does not count for Object. String as a key in Object is fine, but we can’t use another Object as a key in Object.

Let’s try:

As visitsCountObj is an object, it converts all Object keys, such as john and ben above, to same string "[object Object]". Definitely not what we want.

How Map compares keys

To test keys for equivalence, Map uses the algorithm SameValueZeroarrow-up-right. It is roughly the same as strict equality ===, but the difference is that NaN is considered equal to NaN. So NaN can be used as the key as well.

This algorithm can’t be changed or customized.

Chaining

Every map.set call returns the map itself, so we can “chain” the calls:

For looping over a map, there are 3 methods:

For instance:

The insertion order is used

The iteration goes in the same order as the values were inserted. Map preserves this order, unlike a regular Object.

Besides that, Map has a built-in forEach method, similar to Array:

When a Map is created, we can pass an array (or another iterable) with key/value pairs for initialization, like this:

If we have a plain object, and we’d like to create a Map from it, then we can use built-in method Object.entries(obj)arrow-up-right that returns an array of key/value pairs for an object exactly in that format.

So we can create a map from an object like this:

Here, Object.entries returns the array of key/value pairs: [ ["name","John"], ["age", 30] ]. That’s what Map needs.

We’ve just seen how to create Map from a plain object with Object.entries(obj).

There’s Object.fromEntries method that does the reverse: given an array of [key, value] pairs, it creates an object from them:

We can use Object.fromEntries to get a plain object from Map.

E.g. we store the data in a Map, but we need to pass it to a 3rd-party code that expects a plain object.

Here we go:

A call to map.entries() returns an iterable of key/value pairs, exactly in the right format for Object.fromEntries.

We could also make line (*) shorter:

That’s the same, because Object.fromEntries expects an iterable object as the argument. Not necessarily an array. And the standard iteration for map returns same key/value pairs as map.entries(). So we get a plain object with same key/values as the map.

A Setarrow-up-right is a special type collection – “set of values” (without keys), where each value may occur only once.

Its main methods are:

The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason why each value appears in a Set only once.

For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.

Set is just the right thing for that:

The alternative to Set could be an array of users, and the code to check for duplicates on every insertion using arr.findarrow-up-right. But the performance would be much worse, because this method walks through the whole array checking every element. Set is much better optimized internally for uniqueness checks.

We can loop over a set either with for..of or using forEach:

Note the funny thing. The callback function passed in forEach has 3 arguments: a value, then the same value valueAgain, and then the target object. Indeed, the same value appears in the arguments twice.

That’s for compatibility with Map where the callback passed forEach has three arguments. Looks a bit strange, for sure. But this may help to replace Map with Set in certain cases with ease, and vice versa.

The same methods Map has for iterators are also supported:

Maparrow-up-right – is a collection of keyed values.

Methods and properties:

The differences from a regular Object:

  • Any keys, objects can be keys.

  • Additional convenient methods, the size property.

Setarrow-up-right – is a collection of unique values.

Methods and properties:

Iteration over Map and Set is always in the insertion order, so we can’t say that these collections are unordered, but we can’t reorder elements or directly get an element by its number.

Last updated