0

I have a text-file with following data:

[2, 3, 4]
[1, 3, 2]

When i read the file with fs.read i got Strings like this:

'[2,3,4]'
'[1,3,4]'

And because of that the length of my matrix mat is wrong.

Code:

var mat = [];

var fs = require('fs');
fs.readFile('./data/outfilename', function(err, data) {

  if (err) throw err;
  var array = data.toString().split(/\r?\n/);



  for (var i = 0; i < array.length; i++) {

    if (array[i].length > 0) {
      mat.push(array[i]);
    }
  }

  console.log(mat.length);
  console.log(mat[0].length);



});

How i convert the read-line to an array with numbers?

Sully
  • 169
  • 3
  • 13

3 Answers3

2

You can use JSON.parse to convert the strings in the array to array of numbers:

var array = ['[2,3,4]', '[1,3,4]'];

mat =  array.map(s => JSON.parse(s));

console.log(mat);
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

You can parse the string as JSON:

// dummy data
var array = ['[2,3,4]', '[18,4,3]'];

var mat = [];
for (var i = 0; i < array.length; i++) {
  mat.push(JSON.parse(array[i]));
}

console.log(mat);

Or using map:

// dummy data
var array = ['[2,3,4]', '[18,4,3]'];

var mat = array.map(JSON.parse);

console.log(mat);
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
1
var matrix = array.map(JSON.parse)

will transform your array into the matrix that you want.

The strings at each line are JSON representations of array of numbers, so when you apply JSON.parse on each line you have the corresponding array.

Serge Kireev
  • 176
  • 1
  • 8