Ben Wong Ben Wong - 25 days ago 17
Javascript Question

Using javascript to read a csv txt file and load results into an array

I'm trying to use javascript to read a txt file with the contents in a CSV format, parse through it and load it into a single array so I can do math operations to it like (sum, average, standard deviation). I got as far as reading the textfile and I need help with parsing through it.

Thanks!

inputExample.txt

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


index.html

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="file" id="openFile" />
<br>
<pre id="fileContents"></pre>
<script type="text/javascript" src="app.js"></script>
</body>
</html>


app.js

document.getElementById("openFile").addEventListener('change', function(){
var fr = new FileReader();
fr.onload = function(){
// document.getElementById("fileContents").textContent = this.result;
console.log(this.result);


}
fr.readAsText(this.files[0]);
})

Answer
var arr = this.result.split(',');

If your content is also separated by new lines as your example you could replace them with commas and then split them.

var arr = this.result.replace(/\n/g, ',').split(',');
Comments