Search code examples
javascriptjquerytraversal

How to prevent .map from creating duplicate results from nested table?


I'm trying to apply the map method to a dynamically created table in order to select the span elements with class = book_info. The results array contains duplicate data because of the nested table, but I'm not sure why - can someone please explain? What is the correct way to apply the map method to this table to get the desired data? Or should I use the each method instead?

var $table = $("#table_0");

var textbook_data = $table.find('tbody tr').map(function() {
  return $(this).find("span.book_info").html();
}).toArray();
console.log(textbook_data); //view results

//display results
var output = "";
textbook_data.forEach(function(item) {
  output += "<p>" + item + "</p>";
});
$("#array_results").empty().append(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_0">
  <tbody>
    <tr>
      <td><span class="book_info"><img src="https://covers.openlibrary.org/b/id/10131432-M.jpg?default=false"></span></td>
      <td valign="middle">
        <table id="info">
          <tbody>
            <tr>
              <td><b>Title: </b><span class="book_info"><b>Advanced Accounting (13th Edition)</b></span></td>
            </tr>
            <tr>
              <td valign="top"><b>Publisher: </b><span class="book_info">Pearson</span></td>
            </tr>
            <tr>
              <td valign="top" style="padding:0px;">
                <table id="authors">
                  <tbody>
                    <tr>
                      <td valign="top"><b>Author(s): </b></td>
                      <td valign="top" style="padding-left:0px;"><span class="book_info">Bruce Bettinghaus<br>Joseph H. Anthony<br>Floyd A. Beams<br>Smith, Kenneth<br></span></td>
                    </tr>
                  </tbody>
                </table>
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>
<br>
<div id="array_results"></div>


Solution

  • Thank you to @charlietfl

    $("#table_0 > tbody > tr").each(function() {
      textbook_data = $(this).find("td span.book_info").map(function() {
        return $(this).html();
      }).toArray();
    });
    console.log(textbook_data);