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!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/javascript-read-csv-array/” title=”Javascript Read CSV File Into An Array” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

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.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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 *