Format data as a text table in JavaScript
Advanced · 4 min read
Command-line tools print tables like this all the time:
Product | Qty | Price
Rice, 50kg | 2 | 45000
Palm oil | 12 | 1200
Extremely lon… | 1 | 999
Every column lines up, each one is just wide enough for its widest value, and a value that is far too long is cut short with … so it can't stretch the whole table. Building this teaches you to plan before you print: measure everything first, then lay it out.
In this tutorial you will write columnWidths, cell and formatTable. You should know map, join, slice and padEnd. Math.max with spread and the rule for the ellipsis are explained below.
Measure first, then draw
You can't pad the first row until you know how wide each column will be, and that depends on every row. So the work happens in two passes:
- Go through all the rows and find the widest value in each column. Cap it at a limit, so one very long value can't make the table huge.
- Go through the rows again and pad or cut each value to its column's width.
The ellipsis comes out of the budget
If a value is too long for its column, cut it and add …. The … is one character, and it has to fit inside the width. So for a column 14 wide, keep 13 characters and add the ellipsis. If you kept 14 and then added it, that row would be one character wider than the others, and the columns would no longer line up.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
63 Format a text table
hardLay out rows of text as aligned columns. Each column is as wide as its widest value, up to a limit; anything over the limit is truncated with an ellipsis; every line comes out the same width.
Stuck? Three hints, smallest first
- 1. Compute the width of each column from the data before rendering anything.
- 2. Cap it with
Math.min, so one long value cannot stretch the table. - 3. Truncating costs one character for the ellipsis, then
padEndbrings the cell back to width.
Step 1: the widest value in one column
const rows = [
['Product', 'Qty', 'Price'],
['Rice, 50kg', '2', '45000'],
['Palm oil', '12', '1200'],
['Extremely long product name', '1', '999'],
];
const lengths = rows.map((r) => r[1].length);
console.log(lengths); // [ 3, 1, 2, 1 ]
console.log(Math.max(...lengths)); // 3
rows.map((r) => r[1].length) collects the length of the second value in every row. Math.max takes separate numbers, not an array, so ... spreads the array into separate arguments. The widest value in the Qty column is the header, 3 characters.
Step 2: every column, with a cap
const rows = [
['Product', 'Qty', 'Price'],
['Rice, 50kg', '2', '45000'],
['Palm oil', '12', '1200'],
['Extremely long product name', '1', '999'],
];
const columnWidths = (rows, limit) =>
rows[0].map((_, i) => Math.min(limit, Math.max(...rows.map((r) => r[i].length))));
console.log(columnWidths(rows, 14)); // [ 14, 3, 5 ]
Mapping over the first row gives one result per column. i is the column's index; _ is the header value, which we don't need here. The long product name is 27 characters, so Math.min(14, 27) caps the first column at 14. The other two are only as wide as their widest value.
Step 3: one cell, padded or cut
const cell = (text, width) =>
(text.length > width ? text.slice(0, width - 1) + '…' : text).padEnd(width);
console.log(JSON.stringify(cell('Palm oil', 14))); // "Palm oil "
console.log(cell('Extremely long product name', 14)); // 'Extremely lon…'
console.log(cell('Extremely long product name', 14).length); // 14
A short value is padded on the right with spaces until it is width long. A long value keeps width - 1 characters and gets the …, which brings it to exactly width. padEnd then has nothing to add.
Step 4: the natural wrong turn
const wrongCell = (text, width) =>
(text.length > width ? text.slice(0, width) + '…' : text).padEnd(width);
console.log(wrongCell('Extremely long product name', 14).length); // 15
Cutting to the full width and then adding the ellipsis makes the cell 15 wide. padEnd never shortens a string, so nothing fixes it, and that row would be pushed one character to the right.
Step 5: build the table
const rows = [
['Product', 'Qty', 'Price'],
['Rice, 50kg', '2', '45000'],
['Palm oil', '12', '1200'],
['Extremely long product name', '1', '999'],
];
const columnWidths = (rows, limit) =>
rows[0].map((_, i) => Math.min(limit, Math.max(...rows.map((r) => r[i].length))));
const cell = (text, width) =>
(text.length > width ? text.slice(0, width - 1) + '…' : text).padEnd(width);
const formatTable = (rows, limit) => {
const widths = columnWidths(rows, limit);
return rows.map((r) => r.map((c, i) => cell(c, widths[i])).join(' | '));
};
const table = formatTable(rows, 14);
for (const line of table) console.log(line);
console.log(new Set(table.map((l) => l.length)).size); // 1
console.log(table[0].length); // 28
For each row, every value is turned into a cell of its column's width, and the cells are joined with ' | '. The loop prints the table at the top of this page. Putting all the line lengths in a Set keeps only the different ones; a size of 1 proves every line is the same width: 14 + 3 + 5 for the columns plus 6 for the two separators, which is 28.
Step 6: numbers on the right
Numbers are easier to compare when their last digits line up. That means padding on the left instead:
console.log(JSON.stringify('999'.padEnd(5))); // "999 "
console.log(JSON.stringify('999'.padStart(5))); // " 999"
padEnd aligns left; padStart aligns right. A table that right-aligns its number columns would choose one or the other per column.
Limits worth knowing
This counts characters, so it only lines up in a monospaced font, where every character is the same width, such as a terminal. It also counts code units, so an emoji, which takes two, would make its cell look one column short.
The full solution
The panel has the three functions and prints the table and its column widths. Press Run, then read the checks underneath.
const rows = [
['Product', 'Qty', 'Price'],
['Rice, 50kg', '2', '45000'],
['Palm oil', '12', '1200'],
['Extremely long product name', '1', '999'],
];
const LIMIT = 14;
// Widest value per column, capped, so one long cell cannot stretch the table.
const columnWidths = (rows, limit) =>
rows[0].map((_, i) => Math.min(limit, Math.max(...rows.map((r) => r[i].length))));
// Truncation spends one character on the ellipsis, then pads back to width.
const cell = (text, width) =>
(text.length > width ? text.slice(0, width - 1) + '…' : text).padEnd(width);
const formatTable = (rows, limit) => {
const widths = columnWidths(rows, limit);
return rows.map((r) => r.map((c, i) => cell(c, widths[i])).join(' | '));
};
const table = formatTable(rows, LIMIT);
const widths = columnWidths(rows, LIMIT);
for (const line of table) console.log(line);
console.log('column widths:', widths);
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first column is capped at the limit', widths[0], 14);
test('the others are only as wide as their widest value', widths.slice(1), [3, 5]);
test('every line comes out the same width', new Set(table.map((l) => l.length)).size, 1);
test('which is the columns plus two separators', table[0].length, 14 + 3 + 5 + 6);
test('the header row reads properly', table[0], 'Product | Qty | Price');
test('a short value is padded on the right', table[1], 'Rice, 50kg | 2 | 45000');
test('an over-long value is cut and marked', table[3].slice(0, 14), 'Extremely lon…');
test('the ellipsis comes out of the budget, not on top of it', table[3].slice(0, 14).length, 14);
test('and the rest of that row still lines up', table[3].trimEnd(), 'Extremely lon… | 1 | 999');
test('left alignment is padEnd; a numeric column wants padStart instead', '999'.padStart(5), ' 999');
This is the whole section in one function: Math.max over lengths, Math.min to cap, slice to truncate, … to mark it, padEnd to align, join to assemble. Nothing here is new after the previous sixty-two.
Two decisions are worth stating. Deriving the widths from the data means the table cannot be broken by an unexpectedly long value, only capped. And truncating inside the budget rather than appending the ellipsis afterwards is what keeps every line the same width — the mistake is slice(0, width) + '…', which is one character too wide, every time.
Column alignment counted in characters only works in a monospaced font, and it counts code units, so a cell containing an emoji will be one column narrow on screen. For a terminal that is fine. For anything proportionally spaced, alignment belongs to the layout, not to the string.
Common mistakes
- Adding the ellipsis after cutting to the full width. The cell is one character too wide. Cut to
width - 1. - Working out widths from the header only. A longer value further down breaks the alignment. Measure every row.
- Passing an array to
Math.max.Math.max([3, 1])isNaN. Spread it:Math.max(...lengths).
Try it yourself
- Right-align the Qty and Price columns using
padStart. - Add a separator line of dashes under the header, as wide as the table.
- Give each column its own limit, passed in as an array.