How to Get the First Element from Map using JavaScript

JavaScript get first element from map Example tutorial explained you how to get the first element from map using JavaScript;

Example 1:

To get the first element of a Map. The Map keys() and values() methods return an iterator object that contains the Map’s keys and values.

const map = new Map();

map.set('one', 1);
map.set('two', 2);

const [firstKey] = map.keys();
console.log(firstKey); // one

const [firstValue] = map.values();
console.log(firstValue); // 1

Example 2:

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

const map = new Map();

map.set('one', 1);
map.set('two', 2);

const first = [...map][0];

console.log(first); // ['one', 1]

Example 3:

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

const map = new Map();

map.set('one', 1);
map.set('two', 2);

const iterator = map.entries();

const firstIteration = iterator.next(); // {value: ['one', 1], done: false}

const first = firstIteration.value;

console.log(first); // ['one', 1]