How to Get Index Inside map() in JavaScript


How can we get the index of the current iteration inside a map() function?

Example scenario

Suppose we have an array we want to iterate over using the map() function.

const lst = [1, 2, 3];
lst.map((elem) => {
  console.log(`Element: ${elem}`);
  return elem;
});

How can we access the index of the current iteration inside the map() callback function? Without a for loop, this process isn’t as intuitive without reading the docs.

Getting the index in map()

We can get the index of the current iteration using the 2nd parameter of the map() function.

const lst = [1, 2, 3];
lst.map((elem, index) => {
  console.log(`Element: ${elem}`);
  console.log(`Index: ${index}`);
  return elem;
});

From the MDN Web Docs, the following are the parameters for the map() function.

  1. currentValue: the current element being processed in the array.
  2. index: the index of the current element being processed in the array.
  3. array: the array map was called upon.