Index inside map() function

馋奶兔 提交于 2019-11-27 10:42:07
Samuel Toh

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

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.

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

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);

Other arguments of Array.prototype.map():

  • The third argument of the callback function exposes the array on which map was called upon
  • The second argument of Array.map() is a object which will be the this value for the callback function. Keep in mind that you have to use the regular function keyword in order to declare the callback since an arrow function doesn't have its own binding to the this keyword.

For example:

const array = [1, 2, 3, 4];

const thisObj = {prop1: 1}


const map = array.map( function (x, index, array) {
  console.log(array);
  console.log(this)
}, thisObj);

Using Ramda:

import {addIndex, map} from 'ramda';

const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return 'X';
}, list);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!