How to create a array of arrays (or matrix) from a txt file data (javascript)

Viewed 42
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.

1 Answers
  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);

Related