Skip to content

Instantly share code, notes, and snippets.

@rokobuljan
Last active Jul 27, 2019
Embed
What would you like to do?
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