Say I have ha matrix or 2D-array,
const matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
(but with much larger dimensions) and want to print this matrix to the console. I can easily do this with console.log(matrix) and for small matrices this is sufficient. But for larger matrices, at least in node.js, the output can be something like this:
[
[
1,2,
3
],
[
4,5,
6
],
[
7,8,
9
]
]
Now this is obviously exaggerated and e.g 1,2,3 will actually fit into a single line. But for larger dimensions it will not, even though there is plenty of screen space for it.
So I would like to map the matrix into a string, something like this: "1 2 3\n4 5 6\n7 8 9". So that the output would be forced to be
1 2 3
4 5 6
7 8 9
This is assuming there is enough screen space for the width of the matrix.
Due to some numbers possibly being longer than others, using column separators like , or tabs in between the numbers would also be fine. For example
1,2,3
4,555,6,
7,8,9
or even better, most preferably
1 2 3
4 555 6
7 8 9
I know console.table can bring me closer to what I'm seeking but I think it has a little too much clutter and unnecessary stuff in the way, which makes it harder to visualize and comprehend the matrix. I just want a pure minimalistic string.
You could map strings, get the max lenght anf pad the columns.
By selecting padEnd (left) or padStrart (right), you could even change the orientation.
const
data = [[1, 2, 3], [4, 555, 6], [7, 8, 9]],
sizes = Array(data[0].length).fill(0),
result = data
.map(a => a.map((v, i) => {
const s = v.toString();
if (sizes[i] < s.length) sizes[i] = s.length;
return s;
}))
.map(a => a.map((s, i) => s.padEnd(sizes[i])).join(' '))
.join('\n');
console.log(result);