Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
jQuery array to HTML table.


Jquery is required for this function.

The function above will turn and array into a html table with optional th, thead and tfoot elements. The returned data is a jquery object ready for appending or whatever you want to do.

It accepts a simple nested array as the first argument and an array of options as the second.


var data = [
	['Name', 'Age', 'Email],
	['John Doe', '27', ''],
	['Jane Doe', '29', '']

var table = arrayToTable(data, {
	thead: true,
	attrs: {class: 'table'}


Produces this:

<table class="table">
            <td>John Doe</td>
            <td>Jane Doe</td>


  • If you use this on a site wit untruested input you may want to change the .html() calls to .text() to the values will be escaped
var arrayToTable = function (data, options) {
"use strict";
var table = $('<table />'),
rows = [],
defaults = {
th: true, // should we use th elemenst for the first row
thead: false, //should we incldue a thead element with the first row
tfoot: false, // should we include a tfoot element with the last row
attrs: {} // attributes for the table element, can be used to
options = $.extend(defaults, options);
// loop through all the rows, we will deal with tfoot and thead later
for (i = 0; i < data.length; i = i + 1) {
row = $('<tr />');
for (j = 0; j < data[i].length; j = j + 1) {
if (i === 0 && {
row.append($('<th />').html(data[i][j]));
} else {
row.append($('<td />').html(data[i][j]));
// if we want a thead use shift to get it
if (options.thead) {
thead = rows.shift();
thead = $('<thead />').append(thead);
// if we want a tfoot then pop it off for later use
if (options.tfoot) {
tfoot = rows.pop();
// add all the rows
for (i = 0; i < rows.length; i = i + 1) {
// and finally add the footer if needed
if (options.tfoot) {
tfoot = $('<tfoot />').append(tfoot);
return table;

This comment has been minimized.

Copy link

commented Oct 30, 2017

['Name', 'Age', 'Email],

should be:
['Name', 'Age', 'Email'],

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.