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

202
Views
How to create a array of arrays (or matrix) from a txt file data (javascript)
const fs = require('fs');
fs.readFile('input.txt', 'utf8',(err,data)=>{
    if(err){
        console.error(err);
        return;
    }
    console.log(data);
});

I have this code I found on a youtube tutorial, it just reads the data from the text file, now I have this:

1 0 1 0 1
1 0 1 0 1
0 0 0 0 1
1 0 1 0 0
1 0 0 0 1

Now, in order to work with that data I have to make it look like this:

[[1,0,1,0,1],
 [1,0,1,0,1],
 [0,0,0,0,0],
 [1,0,1,0,0],
 [0,0,0,0,1]];

Only restriction is that I can´t use loops in this assigment (while & for loops), every function that is build in javascript is allowed, I can also use the Underscore library (https://underscorejs.org/)

I am just starting with Javascript, please let me know if there is some useful function or something that I can do to make it, thanks in advance.

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

0

  1. .trim() whitespace from both ends of string:
    txt.trim()
    
  2. .split() at each line break \n:
    txt.trim().split(/\n/)
    // ["1 0 1 0 1", "1 0 1 0 1", "0 0 0 0 1", "1 0 1 0 0", "1 0 0 0 1"]
    
  3. .map() to each string in array and .split() at each \s:
    txt.trim().split(/\n/).map(row => row.split(/\s/))
    // See example for output
    
  4. .map() to each sub-array then .map() to convert string into a real number:
    lines.map(row => row.map(bit => +bit));
    // See example for output
    

// Utility function
const log = data => console.log(JSON.stringify(data));

const txt = `
1 0 1 0 1
1 0 1 0 1
0 0 0 0 1
1 0 1 0 0
1 0 0 0 1`;

// Result is an array of string arrays
const lines = txt.trim().split(/\n/).map(row => row.split(/\s/));
log(lines);

// Convert the strings into real numbers
const bits = lines.map(row => row.map(bit => +bit));
log(bits);

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!