Home > Net >  Pretty print an array to a table
Pretty print an array to a table

Time:11-12

I have an array something like [['a','b','c', 'd'],['e','f','g', 'h']]

I want to print it like in javascript

 ---- ---------- ------ -------- 
| a  |  b       |  c   |  d     |
 ---- ---------- ------ -------- 
| e  |  f       |  g   |  h     |
 ---- ---------- ------ -------- 

I know there is method console.table but I can't use it in my case, is there any way to format it using just string padding ? and print that string ?

Or is there any library that can format it like this ?

CodePudding user response:

table is the package you are looking for

https://www.npmjs.com/package/table

import { table } from 'table';

const data = [
    ['a', 'b', 'c', 'd'],
    ['e', 'f', 'g', 'h'],
];

console.log(table(data));

// prints:
// ╔═══╤═══╤═══╤═══╗
// ║ a │ b │ c │ d ║
// ╟───┼───┼───┼───╢
// ║ e │ f │ g │ h ║
// ╚═══╧═══╧═══╧═══╝

Also with custom columns width

import { table } from 'table';

const data = [
    ['a', 'b', 'c', 'd'],
    ['e', 'f', 'g', 'h'],
];

const config = {
  columns: {
    1: { width: 5 },
    3: { width: 3 },
  }
};

console.log(table(data, config));

// prints:
// ╔═══╤═══════╤═══╤═════╗
// ║ a │ b     │ c │ d   ║
// ╟───┼───────┼───┼─────╢
// ║ e │ f     │ g │ h   ║
// ╚═══╧═══════╧═══╧═════╝

The style of the tables are customizable, the documentation has great examples

  • Related