0

I have two arrays and need to write the data from both to two columns of a table. At this point I can write correctly data from the first array only and when I want to add the second array data, it gets added into rows.

orderGelen and userNameArr are my arrays. Here you can see my code:

for(let data of orderGelen){ 
   dataHtmlIds += `<tr><td>${data}</td>`;
}

for(let usr of userNameArr){ 
   dataHtmlUsr += `<td>${usr}</td></tr>`;

}

dataHtml = dataHtmlIds + dataHtmlUsr;
console.log(dataHtml);

And here I write that to table:

function tableConfig() { 

    tableBody.innerHTML = dataHtml;
}

How can I make the second column userNameArr data?

1
  • Can you share demo? Commented Mar 13, 2020 at 16:14

2 Answers 2

1

Try to put two arrays in one array like this

        const all = orderGelen.map((item, index) => ({ id: item, username: userNameArr[index] }));
        let html = '<table>';
        for (let row of all) {
            html += `<tr><td>${row.id}</td><td>${row.username}</td></tr>`;
        }
        html+='</table>'

        console.log(html);
Sign up to request clarification or add additional context in comments.

3 Comments

Its working like charm but its make overwriting in previous datas. I can see only last data in table. How can I solve it ?
Yes but I already delete that html variable, I directly add to my table. Its make again.
so right now you have table and you want to add id column and username column to this table ? or you want to add new rows ?
0

you could do something like

var dataHtml = "";
  for (
    let i = 0, j = 0;
    i < userNameArr.length || j < orderGelen.length;
    i++, j++
  ) {
    dataHtml += `<tr>`;
    dataHtml += `<td>${userNameArr[i] ? userNameArr[i] : ""}</td>`;
    dataHtml += `<td>${orderGelen[j] ? orderGelen[j] : ""}</td>`;
    dataHtml += `</tr>`;
  }

and you could write to the table like

  function tableConfig() {  
    tableBody.innerHTML = dataHtml;
   }

Hope this helps

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.