Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda