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 nor third-party libraries 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.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Parse CSV Useful Bits & Links
The End

 

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.

 

1) PARSE CSV INTO 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

This is nothing but a simple CSV file with a list of dummy users. For the uninitiated, how CSV files work is stupidly simple:

  • , Commas are used to denote columns.
  • \r\n New lines are used to denote rows.

Yep, we only need to read the CSV as a string and split it accordingly in the Javascript later.

 

1B) THE HTML

1-csv-array.html
<input type="file" accept=".csv" id="demoA"/>

All we need in the HTML is a file input field that accepts CSV files.

 

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) SPLIT ROWS & COLUMNS
      let data = reader.result.split("\r\n");
      for (let i in data) {
        data[i] = data[i].split(",");
      }
 
      // (B2-2) DONE
      // data = JSON.stringify(data);
      // picker.value = "";
      console.log(data);
    });
    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 CSV file as a string. We need to manually break it into an array.
    • split("\r\n") will separate the rows.
    • split(",") to separate the columns.

 

 

2) PARSE CSV INTO 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.

PARSED CSV = {
  Name : [...],
  Email : [...],
  Number : [...]
}

 

2B) THE HTML

2-csv-object.html
<input type="file" accept=".csv" id="demoB"/>

Once again, we only require a file input field.

 

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) SPLIT ROWS & COLUMNS
      let temp = reader.result.split("\r\n");
      for (let i in temp) {
        temp[i] = temp[i].split(",");
      }
 
      // (B2-2) REARRANGE KEYS & VALUES
      let data = {};
      for (let i in temp[0]) {
        data[temp[0][i]] = [];
        for (let j=1; j<temp.length; j++) {
          data[temp[0][i]].push(temp[j][i]);
        }
      }
 
      // (B2-3) DONE!
      // data = JSON.stringify(data);
      // picker.value = "";
      console.log(data);
    });
    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 into an object.

 

 

USEFUL 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 & LIMITATION

As 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 the larger 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.