Skip to content

Instantly share code, notes, and snippets.

@rokobuljan
Last active July 27, 2019 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rokobuljan/fc723f7c597a21c960675c99e0548b8c to your computer and use it in GitHub Desktop.
Save rokobuljan/fc723f7c597a21c960675c99e0548b8c to your computer and use it in GitHub Desktop.
Pretty Print 2D Array data in terminal or console
/**
* columnify - Pretty Print 2D array to terminal or console
*
* @prop {Array} colsArr 2D array (table)
* @prop {Integer} tabs Number of max tabs (default 0)
* @return {String} Table-ordered values tab-separated with newlines
*/
const columnify = (colsArr, tabs) => {
const cols = colsArr[0].length;
const max = {};
return colsArr.flat().map((v, i) => {
v = (''+v).trim();
const c = i % cols;
let vl = v.length;
if(!(vl % 4)) vl += 1;
const t = Math.ceil(vl / 4);
max[c] |= 0;
if(max[c] < t) max[c] = t;
return {v, c, t};
}).map(ob => {
const td = max[ob.c] + 1 + (tabs||0) - ob.t
return `${ob.v}${'\t'.repeat(td)}${ob.c+1===cols?'\n':''}`
}).join('');
}
/* EXAMPLE:
console.log(
columnify([
["COL 1", "COL 2", " COL 3 "],
["aaaa", "11112", "aaaab"],
["aaaabbbbccc", "1111", "aaa"],
["aaaabbb", "11112222", "aaa"],
], 0)
);
// RESULT
COL 1 COL 2 COL 3
aaaa 11112 aaaab
aaaabbbbccc 1111 aaa
aaaabbb 11112222 aaa
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment