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} />)}
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.
The Map object holds key-value pairs and remembers the original insertion order of the keys.
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.
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} />)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With