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).
I have a matrix in a .txt file, e.g.:
And I want to put it into a matrix (as float variable) in JavaScript (without node.js).
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>
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