Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
How can I create .txt file from parallel JavaScript arrays?

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:

txt file

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: error message

And:

error message

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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'});
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!