How to Get the First Element of a Map in JavaScript


Maps in JavaScript allows you to store key-value pairs. If you find yourself needing to access the first element in a Map, then we can use following approaches.


Using the Spread Operator

One straightforward way to get the first element of a Map is by using the spread operator along with the Map’s entries and destructuring.

JavaScript
const myMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);

// Spread the entries, then destructure the first element
const [firstKey, firstValue] = [...myMap.entries()][0];

console.log(`Key: ${firstKey}, Value: ${firstValue}`);
// Output: Key: a, Value: 1

In this example, we spread the entries of the Map into an array, and then use array destructuring to capture the key and value of the first element. The approach is concise, but it creates an array containing all Map entries, which may not be efficient for large Maps.

Using Map.entries() and .next()

The entries() method of a Map returns a new Iterator object that contains an array of [key, value] for each element in the Map. Combining this with the next() method allows us to retrieve the first element.

JavaScript
const myMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);

// Using entries() and next() to get the first element
const firstElement = myMap.entries().next().value;

console.log(`Key: ${firstElement[0]}, Value: ${firstElement[1]}`);
// Output: Key: a, Value: 1

Here, next() is used to move the iterator forward by one step, and the value property of the result contains the first [key, value] pair.

Using Map.keys() and .next()

Similar to the previous method, you can use the keys() method to get an iterator for the keys and retrieve the first key.

JavaScript
const myMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);

// Using keys() and next() to get the first key
const firstKey = myMap.keys().next().value;

// Accessing the value using the retrieved key
const firstValue = myMap.get(firstKey);

console.log(`Key: ${firstKey}, Value: ${firstValue}`);
// Output: Key: a, Value: 1

This approach provides more granular control, allowing you to separately obtain the first key and then use it to retrieve the corresponding value.


Trade-offs and Considerations

  • Array Destructuring: The spread operator approach is concise, but it creates an array containing all Map entries, which may not be efficient for large Maps.
  • Iterator Methods: Using entries(), keys(), or values() with next() allows for more control but requires additional lines of code.

🧪Practice Coding Problem:

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Write a function getFirstElement that takes a Map as input and returns an object containing the first key and value.

JavaScript
function getFirstElement(inputMap) {
  // > > > 👉 Write code here 👈 < < <
}

// Example usage:
const sampleMap = new Map([
  ['apple', 'red'],
  ['banana', 'yellow'],
  ['grape', 'purple']
]);

const result = getFirstElement(sampleMap);
console.log(result);
// Expected output: { key: 'apple', value: 'red' }
Please attempt before seeing the Answer:
JavaScript
// function getFirstElement, 
// - takes a Map as input, 
// - checks if it's not empty, 
// - and then uses the spread operator and array destructuring
// - to retrieve the first key-value pair. 
// Result is returned as an object containing the first key and value.

function getFirstElement(inputMap) {
  // Check if the Map is not empty
  if (inputMap.size === 0) {
    return null; // Return null for an empty Map
  }

  // Using the spread operator to get the first entry, then destructuring
  const [firstKey, firstValue] = [...inputMap.entries()][0];

  // Return an object with the first key and value
  return { key: firstKey, value: firstValue };
}

Hopefully it will be useful. Keep refining your skills and Happy coding! 😊🚀

Scroll to Top