Last active
July 27, 2019 19:33
-
-
Save rokobuljan/fc723f7c597a21c960675c99e0548b8c to your computer and use it in GitHub Desktop.
Pretty Print 2D Array data in terminal or console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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