Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Nested array to table

I am nervous about asking on Stack Overflow so it would be so nice to get an answer here. I have spent hours on this.

I have a nested array generated from form input. I want each nested array to be a new row. Nothing is working.

http://jsfiddle.net/kLrAJ/

I commented out all of the previous tries. Currently have a conditional in there that is only running once even though it's inside the loop.

2 Answers

Okay, if I understood you correctly, this is what you were trying to accomplish.

My code first generates a two-dimensional array based on the user input, and then creates a table from it.

I used nested Array.prototype.forEach to generate the table.

There are numerous ways to do this, of course. Instead of forEach, you could use Array.prototype.map to generate new arrays containing the elements and then join them. Or even Array.prototype.reduce.

Using array methods makes the code easier to read.

This function may not be applied in every browser for example IE 10 and below.

Array.prototype.forEach should be available in IE 9+, but it can be easily polyfilled, as well.

Question about var $table = $("<table></table>");

I see that you appended to it, but how come in the source it is <table> stuff </table> and not <table></table>stuff

I have seen this before but could you explain? Or is it jQuery functionality?

That's a jQuery functionality. if you pass the jQuery ($) function a string that is not a selector and it contains a single HTML element, it will create that element. Then a jQuery object that refers to the newly created element is created and returned. That's what gets stored in the $table variable. But that HTML element is not a part of the DOM until it's inserted (appended) somewhere.

Could you link me to the documentation or where this is explained? Thanks

Sure. Here you go.

Dino,

Thank you so much! You are truly great!