2d array with fprintf in javascript

In JavaScript, you can create a 2D array using nested arrays. Here's an example of how to create a 2D array:

index.tsx
let myArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
57 chars
6 lines

To write this 2D array to a file using fprintf, you can use nested loops to iterate through each element of the array and write it to the file.

index.tsx
const fs = require('fs');

// Create a 2D array
let myArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Open a file for writing
let file = fs.openSync('output.txt', 'w');

// Write the array to the file using fprintf
for (let i = 0; i < myArray.length; i++) {
  for (let j = 0; j < myArray[i].length; j++) {
    let value = myArray[i][j];
    fs.writeSync(file, '%d ', value);
  }
  fs.writeSync(file, '\n');
}

// Close the file
fs.closeSync(file);
455 chars
24 lines

In this example, we use the fs module to open a file for writing. We then iterate through each element of the array using nested loops. For each element, we use fs.writeSync to write the value to the file using the %d format specifier. We also write a newline character \n after each row of the array to create a 2D structure in the output file.

Finally, we close the output file using fs.closeSync.

gistlibby LogSnag