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

1

How do I get the same output of this array, written in Java, in 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
    
asked by anonymous 16.04.2018 / 19:31

1 answer

0

Javascript has no way of directly defining 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 an array with a certain amount of elements, representing the lines. Then it traverses each of the generated lines to create the columns.

The print part is very similar to the one you have in java, changing only int and System.out , 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've created the columns at the expense of map that mapped each unique value on the line to a new four-filled array with zeros. This fill was done at the expense of fill .

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

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

What can be an alternative to the example, I just used console.log to be more generic and executable here in live snippet .

    
16.04.2018 / 19:59