Javascript Read & Parse CSV File (Into Array Object)

Welcome to a tutorial on how to read and parse a CSV file into an array or object in Javascript. Need to read a CSV file in your project? Yes, it is possible to do so in modern Javascript. No server-side scripts are required – Read on for the examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

READ & PARSE CSV

All right, let us now get into the examples of how to read and parse a CSV file into an array/object in Javascript.

 

EXAMPLE 1) PARSE CSV INTO AN ARRAY

1A) DUMMY CSV

1-dummy.csv
Joa Doe,joa@doe.com,123456
Job Doe,job@doe.com,234567
Joe Doe,joe@doe.com,345678
Joi Doe,joi@doe.com,456789
Jon Doe,jon@doe.com,987654
"Joy, Doe",joy@doe.com,124578

For this example, we will use this list of dummy users. For the uninitiated, CSV files are nothing more than “plain text with formatting”:

  • , Commas are used to denote columns.
  • \r\n New lines are used to denote rows.
  • "Joy, Doe" If a cell contains a comma, it will be enclosed within double quotes.

 

1B) THE HTML

1-csv-array.html
<!-- (A) JS -->
<!-- https://github.com/okfn/csv.js/ -->
<script src="csv.min.js"></script>
<script src="1-csv-array.js"></script>
 
<!-- (B) FILE PICKER -->
<input type="file" accept=".csv" id="demoA">
  1. We will be using a lightweight library called csv.js to parse the CSV into an array.
  2. An HTML file input field to select a CSV file.

 

1C) THE JAVASCRIPT

1-csv-array.js
window.onload = () => {
  // (A) FILE PICKER
  let picker = document.getElementById("demoA");
 
  // (B) READ CSV FILE
  picker.onchange = () => {
    // (B1) GET SELECTED CSV FILE
    let selected = picker.files[0];
 
    // (B2) READ CSV INTO ARRAY
    let reader = new FileReader();
    reader.addEventListener("loadend", () => {
      // (B2-1) PARSE INTO ARRAY
      let csv = CSV.parse(reader.result);
 
      // (B2-2) LOOP THROUGH ROWS & COLS
      for (let row of csv) {
        for (col of row) {
          console.log(col);
        }
      }
 
      // (B2-3) DONE
      // let data = JSON.stringify(data);
      // picker.value = "";
    });
    reader.readAsText(selected);
  };
};

This should be pretty self-explanatory:

  • (A) Get the HTML file picker field – let picker = document.getElementById("demoA")
  • (B) Use a let reader = new FileReader() object to read the selected CSV file.
  • (B2) But of course, the reader will return the entire CSV file as a string. We will have to use the library to parse it into an array – let csv = CSV.parse(reader.result).

 

 

EXAMPLE 2) PARSE CSV INTO AN OBJECT

2A) DUMMY CSV

2-dummy.csv
Name,Email,Number
Joa Doe,joa@doe.com,123456
Job Doe,job@doe.com,234567
Joe Doe,joe@doe.com,345678
Joi Doe,joi@doe.com,456789
Jon Doe,jon@doe.com,987654
"Joy, Doe",joy@doe.com,124578

Look no further, this is the same example. It only has an additional header row that we will use as the key of the object.

DATA = {
  Name : [...],
  Email : [...],
  Number : [...]
}

 

2B) THE HTML

2-csv-object.html
<!-- (A) JS -->
<!-- https://github.com/okfn/csv.js/ -->
<script src="csv.min.js"></script>
<script src="2-csv-object.js"></script>
 
<!-- (B) FILE PICKER -->
<input type="file" accept=".csv" id="demoB">

Once again, it’s the same “load library” and “HTML file picker”.

 

2C) THE JAVASCRIPT

2-csv-object.js
window.onload = () => {
  // (A) FILE PICKER
  let picker = document.getElementById("demoB");
 
  // (B) READ CSV FILE
  picker.onchange = () => {
    // (B1) GET SELECTED CSV FILE
    let selected = picker.files[0];
 
    // (B2) READ CSV INTO ARRAY
    let reader = new FileReader();
    reader.addEventListener("loadend", () => {
      // (B2-1) PARSE INTO ARRAY
      let csv = CSV.parse(reader.result);
 
      // (B2-2) REARRANGE KEYS & VALUES
      let data = {};
      for (let [col,key] of Object.entries(csv[0])) {
        data[key] = [];
        for (let row=1; row<csv.length; row++) {
          data[key].push(csv[row][col]);
        }
      }
      console.log(data);
 
      // (B2-3) DONE!
      // data = JSON.stringify(data);
      // picker.value = "";
    });
    reader.readAsText(selected);
  };
};

Not going to explain this line-by-line, but it’s essentially the same as the previous example.

  • (A & B) Get the selected CSV file and read it.
  • (B2-1) Parse the CSV string into an array first.
  • (B2-2) Loop through the array and rearrange it into an object.

 

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

PERFORMANCE ISSUES & LIMITATIONS

At the time of writing, there are seemingly no ways to read CSV files line-by-line with the FileReader. That is, it will read the entire CSV file into a string all at once. While this works, it will run into performance and memory issues with massive CSV files. So yep, this is one “limitation” to take note of… Until the developers decide to “fix” FileReader and give it a “read line-by-line” feature.

 

COMPATIBILITY CHECKS

Well-supported on modern browsers, but not for the ancient Internet Exploders.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Parse CSV Into Array (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *