Search code examples
javascriptarraysnode.jsmatrixreadfile

Convert Array presented as String


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?


Solution

  • 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);