0

I have a table in a .csv file format, which I need to use in my program. What I need to do is read the file, and then convert it into a two dimensional array/matrix.

I found this code below, which reads a .csv file and converts it into a string, but I don't know how to access the string, and furthermore convert it into an array.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
    <form id="myForm">
        <input type="file" id="csvFile" accept=".csv" />
        <br />
        <input type="submit" value="Submit" />
    </form>
    <script>

        const myForm = document.getElementById("myForm");
        const csvFile = document.getElementById("csvFile");
        myForm.addEventListener("submit", function (e) {
            e.preventDefault();
            const input = csvFile.files[0];
            const reader = new FileReader();
            reader.onload = function (e) {
                const text = e.target.result;
                document.write(text);
            };
            reader.readAsText(input);
        });
    </script>
</body>

</html>

I tried saving the string into a variable, but I keep encoutering errors, like '"text" is not defined' etc. I am very new to JavaScript so please bear with me :)

K_Grabska
  • 1
  • 1
  • and [Javascript loading CSV file into an array](https://stackoverflow.com/questions/23762822/javascript-loading-csv-file-into-an-array) and the 13 year old duplicate [How to parse CSV data?](https://stackoverflow.com/questions/1293147/how-to-parse-csv-data) – pilchard Jan 09 '23 at 22:11
  • I have an answer for the first half. The other half...probably uses `.split`? I've never really used CSV files. – Someone Jan 09 '23 at 22:13

1 Answers1

0

This is the answer for the first half.

When you use FileReader.prototype.readAsText, you have to wait for it to finish. You can use the loadend event to check for this. Then, the FileReader's result property will contain the string.

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

Someone
  • 202
  • 2
  • 13