Create JavaScript Code to read a Comma Separated Value (CSV) text file (it will
ID: 3882267 • Letter: C
Question
Create JavaScript Code to read a Comma Separated Value (CSV) text file (it will have a .txt extension). See the testData.txt file in this module. There are three attributes: Row, Name, Grade, and 10 records.
Create a function named processData that will take the file and put it into a multidimensional array named userData.
Write the contents of the array to a web page.
Compute and write to the web page the average score for the grade attribute rounded to 2 decimal places, you can write a function for this if you wish.
Add student and assignment comments at the top of the code file.
Add informative comments to the code.
Row, Name, Grade
1, Aaron, 3.5
2, Betty, 3.6
3, Charlie, 3.6
4, Debbie, 3.5
5, Eddie, 3.2
6, Farrah, 3.1
7, George, 3.0
8, Haley, 3.0
9, Ira, 3.0
10, Juliet, 3.1
Explanation / Answer
As per your requirement the below one is solution please follow it
<html>
<head>
<title>
Read CSV files
</title>
</head>
<body>
<p>Select local CSV File:</p>
<input id="csv" type="file">
<pre id="out">file contents will appear here
</pre>
<p id="out1"></p>
<script type="text/javascript">
var fileInput = document.getElementById("csv");
var result,line,section; //declaration of required variables
var i;
var userData=[];
count = 0;
processData = function () {
var reader = new FileReader(); //initialization of file reader
var output = document.getElementById("out");
reader.onload = function () {
result = reader.result;
line = result.split(" "); //split the entire file contents into lines and store into an array
for(i=0;i<line.length;i++){
section = line[i].split(","); //again split each line into comma separated values and store into another array
userData[i] = []; //declaration to make the userData array multidimentional
userData[i][0] = section[0];
userData[i][1] = section[1]; //copying of content into the userData array
userData[i][2] = section[2];
var newText = document.createTextNode(userData[i][0]+". "+userData[i][1]+" "+userData[i][2]+" ");//printing of array contents into webpage
output.appendChild(newText);
}
var output1 = document.getElementById("out1");
var sum = 0;
for(i=0;i<line.length;i++){
sum += Number(userData[i][2]); //calculation of sum of grades. here the grade values are converted into number by using Number() method
}
output1.innerHTML = "The average of the grades is : "+(sum/line.length); //calculation and printing of average in webpage
};
// start reading the file. When it is done, calls the onload event defined above.
reader.readAsBinaryString(fileInput.files[0]);
};
fileInput.addEventListener('change', processData);//add event listener to html element for calling of method processData
</script>
</body>
</html>