Having trouble reading a CSV file using file reader in Javascript. I wrote a script that declares arrays and updates them as the file is read. However, once the reading is complete, all data from the arrays gets wiped out. I'm quite new to JS and can't figure out why this is happening. I suspect it has something to do with the scope of the arrays, even though I declared them as global variables. Any help would be appreciated!
var paper = [];
var recyclables = [];
var compost = [];
var landfill = [];
function readCsvFileData(type, index) {
readCsv();
if(type == "paper"){
console.log("requested type - " + paper.length);
console.log("wrong answer here -- 0 ");
return paper[index];
}
}
function readCsv() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
console.log(this.responseText);
var line = this.responseText.split("\n");
for(let row = 1; row < line.length; row++){
let rowData = line[row].split(',');
for(let col = 1; col < rowData.length; col++){
if(col == 1 && paper.length<12){
paper.push(rowData[col]);
}
if(col == 2 && recyclables.length<12){
recyclables.push(rowData[col]);
}
if(col == 3 && compost.length<12){
compost.push(rowData[col]);
}
if(col == 4 && landfill.length<12){
landfill.push(rowData[col]);
}
if(paper.length==12 && recyclables.length==12 && compost.length==12 && landfill.length==12){
console.log("retruning "+landfill.length);
console.log("correct answer here -- 12");
return true;
}
}
}
}
}
xhttp.open('GET', "Data.csv", true);
xhttp.send();
}