1

I have an issue the array is showing undefined even if i am storing the table data into an array https://leetcode.com/tag/array/

Getting every problem's row in the form of an array

function getAllProblemRowElements() {
    //var k = document.querySelector("#app > div > div > div > div.table-responsive > table > tbody");
    const tableContents = document.querySelector("#app > div > div > div > div.table-responsive > table > tbody");
    const sources = Array.from(tableContents,source=>tableContents[0]);
    return sources;

} 

Please resolve it

1
  • Which test is it? Commented Nov 15, 2020 at 8:15

3 Answers 3

1

Table content to Array

var myTableData = Array.prototype.map.call(document.querySelectorAll('#myTable tr'), function(row){
  return Array.prototype.map.call(row.querySelectorAll('td'), function(td){
    return td.innerHTML;
    });
  });

console.log(myTableData)
<table id="myTable">
<tr>
  <td>1</td>
  <td>a</td>
</tr>
<tr>
  <td>2</td>
  <td>b</td>
</tr>
<tr>
  <td>3</td>
  <td>c</td>
</tr>
</table>

Sign up to request clarification or add additional context in comments.

Comments

1

Here is an ES6 version

const myTableData = [...document.querySelectorAll('#myTable tr')]
  .map(row => [...row.querySelectorAll('td')]
    .map(cell => cell.textContent));

console.log(myTableData)
<table>
  <tbody id="myTable">
    <tr>
      <td>1</td>
      <td>a</td>
    </tr>
    <tr>
      <td>2</td>
      <td>b</td>
    </tr>
    <tr>
      <td>3</td>
      <td>c</td>
    </tr>
  </tbody>
</table>

Comments

0

I assume that the problem row defined in your question is the title. You can use the querySelectorAll in document to get all the rows and then map it into an array. Hope the below code helps:

function getAllProblemRowElements() {

    const tableContents = document.querySelectorAll("#app > div > div > div > div.table-responsive > table > tbody > tr");
    const sources = Array.from(tableContents,source=>source.children[2].getAttribute("value"))
    return sources;
}

1 Comment

This is assuming input fields - did you identify the actual problem at leetcode?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.