Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pretty print an array to a table

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading