I have following function that display ASCII table
function ascii_table(array, header) {
if (!array.length) {
return \'\'
You could modify the table and add the new rows to the table before before rendering it:
function ascii_table(array, header) {
if (!array.length) {
return '';
}
//added
for (var i = array.length - 1; i >= 0; i--) {
var row = array[i];
var stacks = [];
for (var j = 0; j < row.length; j++) {
var newLines = row[j].split("\n");
row[j] = newLines.shift();
stacks.push(newLines);
}
var newRowsCount = stacks.reduce(function(a, b) {
return a.length > b.length ? a : b;
}).length;
for (var k = newRowsCount - 1; k >= 0; k--) {
array.splice(i + 1, 0, stacks.map(function(stackColumn) {
return stackColumn[k] || "";
}));
}
}
//added
var lengths = array[0].map(function(_, i) {
var col = array.map(function(row) {
if (row[i] != undefined) {
return row[i].length;
} else {
return 0;
}
});
return Math.max.apply(Math, col);
});
array = array.map(function(row) {
return '| ' + row.map(function(item, i) {
var size = item.length;
if (size < lengths[i]) {
item += new Array(lengths[i] - size + 1).join(' ');
}
return item;
}).join(' | ') + ' |';
});
var sep = '+' + lengths.map(function(length) {
return new Array(length + 3).join('-');
}).join('+') + '+';
if (header) {
return sep + '\n' + array[0] + '\n' + sep + '\n' +
array.slice(1).join('\n') + '\n' + sep;
} else {
return sep + '\n' + array.join('\n') + '\n' + sep;
}
}
Output:
+---------------------+------+--------+-----+------------------+------------+---------------------+
| date | nick | email | www | comment | ip | avatar |
+---------------------+------+--------+-----+------------------+------------+---------------------+
| 2016-01-28 11:40:59 | lol | lol@lo | | nocomment | 1844311719 | avatars/default.png |
| | | l.fr | | lol | | |
| | | | | lol | | |
| | | | | lol | | |
| 2016-01-10 15:13:59 | ehs | what | | ente rm comment. | 1423172924 | avatars/default.png |
+---------------------+------+--------+-----+------------------+------------+---------------------+
(Added a new line in one email cell, to test new lines in multiple columns).