How to Get the First Element from a Map in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

Get the First Element from a Map in JavaScript #

The easiest way to get the first element of a map is to use destructuring assignment.

index.js
const map = new Map(); map.set('a', 1); map.set('b', 2); const [firstKey] = map.keys(); console.log(firstKey); // ๐Ÿ‘‰๏ธ a const [firstValue] = map.values(); console.log(firstValue); // ๐Ÿ‘‰๏ธ 1

In the code snippet we called the keys() method on the map to get an iterator that contains the keys of each element in the map.

We then use destructuring assignment to get the first key and assign it to a variable.

To get the value of the first element, we repeat the same process, but call the values() method instead.

Another way to get the first element from a map is to convert the map into an array and access the element at index 0.

index.js
const map = new Map(); map.set('a', 1); map.set('b', 2); const first = [...map][0]; console.log(first); // ๐Ÿ‘‰๏ธ ['a', 1]

In the code snippet we use the spread syntax to convert the map into an array and access the element at index 0.

This returns an array containing the key and value of the first element in the map.

Note that converting a map with thousands of elements into an array would be slow and inefficient, if you just have to access a single element.

We can also get the first element from a map by using some of the methods on the map instance.

index.js
const map = new Map(); map.set('a', 1); map.set('b', 2); const iterator = map.entries(); const firstIteration = iterator.next(); // {value: ['a', 1], done: false} const first = firstIteration.value; console.log(first); // ๐Ÿ‘‰๏ธ ['a', 1]

In the code snippet, we first get an iterator containing the elements of the map.

We then an object containing the value of the first iteration.

Finally, we access the value property on the object to get an array of the key and value of the first element in the map.

The last approach is harder to read and less intuitive than the first 2. It's best to avoid getting into the implementation details of maps, unless you have to.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee