1

I have very little experience with Javascript arrays. I have a complex enough requirement that I need to put my data into an array and then generate an HTML table. In this example, I have a multi-dimensional array here for a Leaderboard where each value is an array of the team's scores.

I've nested a forEach within a forEach to construct the rows and cells. However, I keep getting two 'undefined' responses at the top, one for each team. I think it has something to do with the thisValue part of the forEach method, but I can't stop it or replace it.

I'm sure this is not the proper way to set this up, but if it's possible to get this working with a minor tweak for now, it would be ideal. See images. Any help is appreciated!

leaderBoard.forEach(row);

function row(value,index,array)
{
    document.write('<tr>' + value.forEach(cell) + '</tr>');
}

function cell(value,index,array)
{
    document.write('<td>' + value + '</td>');
}

enter image description here

When I remove the reference to the cell function from the row function, it returns the arrays and the 'undefinedundefined' disappears. Note below that I removed '.forEach(cell)' and added the data tags.

function row(value,index,array)
{
    document.write('<tr><td>' + value + '</td></tr>');
}

Table without undefined at top

10
  • You're terminating your row with a </td>, not a </tr> Commented Feb 11, 2021 at 1:50
  • 2
    Please read Why not upload images of code on SO when asking a question and edit your question to include code and data as text, not images. Commented Feb 11, 2021 at 1:51
  • It wasn't the <td> tag, I fixed that and it's still the same output. Commented Feb 11, 2021 at 1:58
  • So what exactly is the problem with the output you currently have? Commented Feb 11, 2021 at 2:00
  • The 'undefinedundefined' at the top of the table. It appears to be created within the row function. Commented Feb 11, 2021 at 2:01

1 Answer 1

1

I think this will accomplish what you want

leaderBoard.forEach(function (row) {
  row.forEach(function (cell) {
      document.write('<tr><td>' + cell + '</td></tr>');
    });
});

Your attempt removing the reference to the cell function was close. The problem was that you were writing your entire row into 1 cell

//value = [AM, 90, 76, 67, 233]
function row(value,index,array)
{
    document.write('<tr><td>' + value + '</td></tr>');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.