Zygimantas Berziunas Zygimantas Berziunas - 4 months ago 22
Javascript Question

Index inside map() function

I am missing a option how to get the index number inside the

map
function using
List
from
Immutable.js
:

var list2 = list1.map(mapper => { a: mapper.a, b: mapper.index??? }).toList();


Documentation shows that
map()
returns
Iterable<number, M>
. Is there any elegant way to what I need?

Answer

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

See: https://developer.mozilla.org/enUS/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.

Example:

var 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 'X';
});

Output:

The current iteration is: 0
The current element is: h

The current iteration is: 1
The current element is: e

The current iteration is: 2
The current element is: l

The current iteration is: 3
The current element is: l

The current iteration is: 4
The current element is: o