Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda