How to Get the First Element of a Map in JavaScript (Easy Ways)

In this article, we’ll be exploring some ways to quickly get the first element of a Map object in JavaScript.

1. Call next() on Map entries()

To get the first element of a Map, we can call the entries() on the Map to get an iterable object, then call the next() method on this iterable. For example:

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3'],
]);

const firstElement = map.entries().next().value;

console.log(firstElement); // [ 'key1', 'value1' ]

The Map entries() method returns an iterable of key-value pairs for all elements of the Map. The next() method returns the next element in the iterable sequence. Since it’s the first time we’re calling it on the iterable, it returns the first element in the sequence. We use the value property of the element to get the key-value pair representing the first element of the Map.

2. Array.from()

We can also use the Array.from() method to get the first element of the Map:

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3'],
]);

const firstElement = Array.from(map)[0];
console.log(firstElement); // [ 'key1', 'value1' ]

Note

On a Map with many elements, this method is significantly slower than the first, as it creates a new array from all the Map elements. We conducted a performance comparison between the two methods on a Map with 1 million elements, and these were the results on average:

Iterable next(): 0.015ms
Array from() 251.093ms


Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *