✒️
Here are my favorite tips to land the software engineer interview.
Here are my favorite tips to land the software engineer interview.
How to Get Index Inside map() in JavaScript
Published Oct 10, 2021
∙ Updated May 2, 2022
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.
currentValue
: the current element being processed in the array.index
: the index of the current element being processed in the array.array
: the array map was called upon.