Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda