Index inside map() function Index inside map() function javascript javascript

Index inside map() function


You will be able to get the current iteration's index for the map method through its 2nd parameter.

Example:

const list = [ 'h', 'e', 'l', 'l', 'o'];list.map((currElement, index) => {  console.log("The current iteration is: " + index);  console.log("The current element is: " + currElement);  console.log("\n");  return currElement; //equivalent to list[index]});

Output:

The current iteration is: 0 <br>The current element is: hThe current iteration is: 1 <br>The current element is: eThe current iteration is: 2 <br>The current element is: lThe current iteration is: 3 <br>The current element is: l The current iteration is: 4 <br>The current element is: o

See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Parameters

callback - Function that produces an element of the new Array, taking three arguments:

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.


Array.prototype.map() index:

One can access the index Array.prototype.map() via the second argument of the callback function. Here is an example:

const array = [1, 2, 3, 4];const map = array.map((x, index) => {  console.log(index);  return x + index;});console.log(map);