Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
Convert matrix/2D-array of numbers to formatted string

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!