Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sequence number in map function in JavaScript?

Is there a way for me to get the sequence number of each item in a map function in JavaScript?

For example, I have an array of 5 items and would like to pass the sequence number of each item to my React component in the following code:

{toDoList.map(item => <ToDoItem key={item.id} sequenceNumber={???} data={item} />)}
like image 370
Sam Avatar asked Sep 17 '17 23:09

Sam


People also ask

What is .map number?

The . map() method allows you to loop over every element in an array and modify or add to it and then return a different element to take that elements place. However . map() does not change the original array.

Does JS map retain order?

The Map object holds key-value pairs and remembers the original insertion order of the keys.

What is the return value of the map method?

Return Value: It returns a new array and elements of arrays are result of callback function. Below examples illustrate the use of array map() method in JavaScript: Example 1: This example use array map() method and return the square of array element.


1 Answers

the three parameters to callback function inside map are element, index and array itself, so you only need to give a second argument to callback function like:

var arr = [1,2,3,4];

arr.map((num, index) => console.log(num + " " + index));

so in your case it will be:

{toDoList.map((item, index) => <ToDoItem key={item.id} sequenceNumber={index} data={item} />)}
like image 79
Dij Avatar answered Sep 27 '22 23:09

Dij