I know this is an old question, but for those perusing the web like me, here's another solution:
Use replace()
on the commas and create a set of characters to determine the end of a row. I just add --
to end of the internal arrays. That way you don't have to run a for
function.
Here's a JSFiddle: https://jsfiddle.net/0rpb22pt/2/
First, you have to get a table inside your HTML and give it an id:
<table id="thisTable"><tr><td>Click me</td></tr></table>
Here's your array edited for this method:
thisArray=[["row 1, cell 1__", "row 2, cell 2--"], ["row 2, cell 1__", "row 2, cell 2"]];
Notice the added --
at the end of each array.
Because you also have commas inside of arrays, you have to differentiate them somehow so you don't end up messing up your table- adding __
after cells (besides the last one in a row) works. If you didn't have commas in your cell, this step wouldn't be necessary though.
Now here's your function:
function tryit(){
document
.getElementById("thisTable")
.innerHTML="<tr><td>"+String(thisArray)
.replace(/--,/g,"</td></tr><tr><td>")
.replace(/__,/g,"</td><td>");
}
It works like this:
- Call your table and get to setting the
innerHTML
. document.getElementById("thisTable").innerHTML
- Start by adding HTML tags to start a row and data.
"<tr><td>"
- Add
thisArray
as a String()
. +String(thisArray)
- Replace every
--
that ends up before a new row with the closing and opening of data and row. .replace(/--,/g,"</td></tr><tr><td>")
- Other commas signify separate data within rows. So replace all commas the closing and opening of data. In this case not all commas are between rows because the cells have commas, so we had to differentiate those with
__
: .replace(/__,/g,"</td><td>")
. Normally you'd just do .replace(/,/g,"</td><td>")
.
As long as you don't mind adding some stray characters into your array, it takes up a lot less code and is simple to implement.