Search code examples
javascripthtmlarraysmultidimensional-arrayundefined

When i want to use 2 dimensional array it returns me undefined


I work with database which I input.

I declared array and wanted to push another array in first one.

When I try to use my 2 dimensional array, console returned undefined.

let dataAboutCovid = [];
let date, totalCases, todayCases, recovered;
let country = "USA";

//Read file from input
//Control if country exist
//Put data about covid in dataAboutCovid

function readFile(input) {
  let database;

  for (i = 0; i < input.files.length; i++) {

    let reader = new FileReader();
    reader.readAsText(input.files[i]);

    reader.onload = function(e) {
      database = e.target.result;

      let arrayOfCountry = database.split(`\n`).find((item) => item.includes(country))
      if (!arrayOfCountry) {
        return
      }
      if (arrayOfCountry.slice(0, 3) == ",,,") {
        date = arrayOfCountry.slice(3, this.length).split(",")[1].split(" ")[0];
        totalCases = arrayOfCountry.slice(3, this.length).split(",")[4];
        todayCases = arrayOfCountry.slice(3, this.length).split(",")[5];
        recovered = arrayOfCountry.slice(3, this.length).split(",")[6];
        dataAboutCovid.push([date, totalCases, todayCases, recovered]);
      }
    }
  };

  console.log(dataAboutCovid[1][1])
}


Solution

  • I see two issues.

    • When i is 0, you would only fill up dataAboutCovid[0], so dataAboutCovid[1] is undefined
    • There's a possibility that console.log is executed before reader.onload due to the asynchronous nature of js.