1

I have a matrix in a .txt file, e.g.:

1 3 4 5 1

4 2 5 1 3

2 4 5 6 7

5 2 5 2 7

2 2 6 4 7

And I want to put it into a matrix (as float variable) in JavaScript (without node.js).

phi2192
  • 13
  • 3
  • Did you try to solve this exercise yourself? – MarcoS Apr 27 '21 at 07:40
  • 1
    This is actually 2 questions; the first part of the question is "how to read a file in js, without nodejs" The second is "how to convert a string with newlines and spaces to a matrix" I suggest you to split this question in 2 separate ones – Francesco Manicardi Apr 27 '21 at 09:34

2 Answers2

1

You need FileReader object to read the contents of the file.

var reader = new FileReader();

Then when the file is loaded, using the .result property, you can read the content of the files.

var text = reader.result;

Now, the data from the text file will be in strings format.

1 3 4 5 1
4 2 5 1 3
2 4 5 6 7
5 2 5 2 7
2 2 6 4 7

You need to read each line check for \n(which is newline)

Below is the demo code:

var openFile = function(event) {
  var input = event.target;

  var reader = new FileReader();
  reader.onload = function() {
    var text = reader.result;
    var node = document.getElementById('output');
    node.innerText = text;
    console.log(reader.result.substring(0, 200));
    let array = reader.result.trim().split("\n").map(str => str.trim().split(" "))
    console.log(array)

  };
  reader.readAsText(input.files[0]);
};
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
</div>
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
0

Once you get the file as a string you can use this piece of code to parse it into a twodimensional array:

var fileContents = "1 3 4 5 1\n4 2 5 1 3\n2 4 5 6 7\n5 2 5 2 7\n2 2 6 4 7";

var array = fileContents.trim().split("\n").map(str => str.trim().split(" "))

console.log(array);

As for loading the file, I'd suggest something like this Open file dialog box in JavaScript