How to print a table-shaped array in nodejs on the console?

Asked

Viewed 1,943 times

1

How do I get the same output from this matrix, written in Java, on Nodejs?

 public class Matriz {
    public static void main(String[] args) {

        int[][] m = new int[4][4];

        for (int i = 0; i < m.length ; i++) {
            for (int j = 0; j < m[i].length ; j++) {
                System.out.print(m[i][j] + " ");
            }
            System.out.println();
        }
    }  
}

exit

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
  • Your question is with javascript tag instead of java. Be careful.

1 answer

0


Javascript has no way for you to directly define the size of an array as it does in java with new int[4][4]. However you can start by defining the initial array with :

new Array(tamanho)

That creates a logo array with a certain amount of elements, which represent the lines. Then scroll through each of the generated rows to create the columns.

The printing part is very similar to the one you have in java by just changing the int and the System.out, for let and console.log respectively.

Example:

let m = new Array(4).fill(0); //criar as linhas e preencher com zeros
m = m.map(linha => new Array(4).fill(0)); //criar as colunas e preencher com zeros

for (let i = 0; i < m.length; i++){
  let escrita = "";
  for (let j = 0; j < m[i].length; j++){
    escrita += m[i][j] + " ";
  }
  console.log(escrita);
}

To be compact I created the columns at the expense of map that mapped each unique value on the line by a new array of size four filled with zeros. This padding was done at the expense of fill.

Note that the example does not have the equivalent of System.out.print that does not change line as it is not possible to use the console.log without changing lines. However, in Node can write without changing lines with:

process.stdout.write(m[i][j] + " ");

Which may be an alternative to the example, I just used console.log to be more generic and executable here on live snippet.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.