I currently have the following code, although poor, as I am unfamiliar with how to write to .txt files using JS.
Here are my parallel arrays:
let myQuestions = ["Where is New York?", "Where is Paris?"];
let myAnswers = ["USA", "France"];
I would like the .txt file to look something like:
I believe that in order to achieve what I desire, I must loop through both arrays using a single for loop, as such:
function addToTxtFile()
{
for(let i = 0; i<myQuestions.length; i++){
addToFile(myQuestions[i], myAnswers[i]);
}
}
Please note that the addToFile method does not exist, I am simply trying to map out the process.
Edit following answer:
HTML:
<button type = 'button' onclick = 'addToTxtFile()'></button>
const fs = require('fs');
const padString = (str) => str.padEnd(padding);
let content = `${padString('Questions:')} ${padString('Answers:')}\n\n`;
let myQuestions = ["Where is New York?", "Where is Paris?"];
let myAnswers = ["USA", "France"];
function addToTxtFile()
{
for (let i = 0; i < myAnswers.length; i++) {
let line = `${padString(myQuestions[i])} ${padString(myAnswers[i])}\n`;
content += line;
}
fs.writeFileSync('out.txt', content, {encoding: 'utf-8'});
}
I am getting the following messages:

And:
You can try something like this:
let myQuestions = ["Where is New York?", "Where is Paris?"];
let myAnswers = ["USA", "France"];
const fileContent = getFileContent(myQuestions, myAnswers);
writeToFile(fileContent);
function getFileContent(questions, answers) {
const padding = 30;
const padString = (str) => str.padEnd(padding);
let content = `${padString('Questions:')} ${padString('Answers:')}\n\n`;
// assuming questions.length === answers.length
for (let i = 0; i < answers.length; i++) {
let line = `${padString(questions[i])} ${padString(answers[i])}\n`;
content += line;
}
return content;
}
function writeToFile(content) {
// assuming NodeJS
const fs = require('fs');
fs.writeFileSync('out.txt', content, {encoding: 'utf-8'});
}