Search code examples
javascriptarraysloopsdatatable

How do I display the row number count in a dynamic javascript table?


I'm looping over an array on the front end using ejs and displaying the data in a bootstrap 5 table. The table is dynamic so rows will be added and deleted with time.

All the data is coming through without an error and the table is populating, however, I'd like to have the first column show the "count" for each row. Eg., "1, 2, 3, 4, 5, etc".

I've tried using indexOf without any success and since the code already exists in a loop, creating another loop requires me to switch my ejs syntax and I lose the ability to count the length of the array.

Below is my client side code that yields value -1 down the entire # column for each row:

 <div class="col-12 d-flex flex-row-reverse">
  <a href="" class="a1" onclick="exportTableToCSV(null, 'text.csv')">Export to csv</a>
 </div>
 <div class="table-responsive">
<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Email</th>
      <th scope="col">Gender</th>
      <th scope="col">Age</th>
      <th scope="col">Clicked IG</th>
      <th scope="col">Date Added</th>
      <th scope="col">Remove</th>
    </tr>
  </thead>
  <tbody>
    <% for (let fan of artist.fans){%>
    <tr>
      <th scope="row"><%= artist.fans.indexOf(fan.id) %></th>
      <td><%= fan.email %></td>
      <td><%= fan.gender %></td>
      <td><%= fan.age %></td>
      <td><%= fan.subscribed %></td>
      <td><%= fan.dateAdded %></td>
      <td style="padding-left: 2rem;">
        <button onclick="removeRow()" ></button>
         </td>
      <td style="padding-left: 2rem;"><i class="bi bi-trash"></i></td>
      <% } %> 
    </tr>
  </tbody>
</table>
</div>

If I switch artist.fans.indexOf(fan.id) with just fan.id I get the corresponding objectId for each fan email object.

If I switch artist.fans.indexOf(fan.id) with artist.fans.length I get 7 down the # column for each row.

Here's my db model:

const artistSchema = new Schema({
image: [ImageSchema], 
genre: [ String ], 
fans: [{ 
    email: String, 
    subscribed: String, 
    gender: String, 
    age: Number 
        dateAdded: {
            type: Date,
            default: Date.now
                }
      }], 
 });

How do I get each row to be numbered?


Solution

  • the problem is that you used fan.id as a search param in artist.fans.indexOf(fan.id) which is not directly accessible throw the artist.fans so instead you need to use another method that accepts comparing function so you can compare their id

    try to use

    <th scope="row"><%= artist.fans.findIndex(f=> f.id == fan.id) %></th>