0

I want to add number to each div when it returns a new div from the map() function.

I have this code here which return a section when a new item push to a array

let displaydata=todoArry.map(item=>{
            return (`
            <div class="todo">

                <p>
                ${item.todo}
                </p>
                <i class="fa-solid fa-trash" onClick=Ui.removeFunc(${item.id})></i>
            </div>
            `)
        })
        list.innerHTML=(displaydata).join(" ")

I want to add number straying from 1 to each div for example if there are 5 item number should be 1 2 3 4 5 like that but if a new item push to the array the number should be update as 1 2 3 4 5 6 like that

I tried like this

let displaydata=todoArry.map(item=>{
            return (`
            <div class="todo">
          <p>${++count}</>

                <p>
                ${item.todo}
                </p>
                <i class="fa-solid fa-trash" onClick=Ui.removeFunc(${item.id})></i>
            </div>
            `)
        })
        list.innerHTML=(displaydata).join(" ")

I add ++count but that's not working.it update all the other numbers as well

mrJsK
  • 1
  • 1
  • 1
    `map` has [an index parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#parameters) - maybe use that. – Andy Feb 05 '23 at 18:02
  • I want to do this without index for learning purpose – mrJsK Feb 05 '23 at 18:09

1 Answers1

-1

You need to define the count variable outside of the map function, so that it is persistent between invocations of the function. Here's an example:

let count = 0;
let displaydata = todoArry.map(item => {
count++;
return ( <div class="todo"> <p>${count}</p> <p>${item.todo}</p> <i class="fa-solid fa-trash" onClick=Ui.removeFunc(${item.id})></i> </div> );
});
list.innerHTML = (displaydata).join(" ");
Martin
  • 39
  • 5