How to Convert CSV to Array in JavaScript

Unraveling the world of JavaScript, we often find ourselves dealing with different types of data. One common format we encounter is CSV (Comma Separated Values), which is a simple file format used to store tabular data, like a spreadsheet or database.

But what if you’re keen to work with this data more fluidly in your JavaScript code? The answer lies in converting your CSV into an array. This creates a more interactive and manipulable data structure, making it easier for you to perform your desired operations. Don’t worry, it’s easier than you might think, and I’m here to guide you through this process.

In this post, we will be looking at the following 3 ways to convert CSV to array in JavaScript:

  • By using the built-in FileReader() method
  • By using the fetch() and response.text() methods
  • By using the Papa Parse library

Let’s explore each…

#1 – By using the built-in FileReader() method

By using the built-in FileReader() method

This process involves reading a CSV file using JavaScript’s FileReader() method, parsing the data into lines, and further splitting those lines into an array of values. An example will help in understanding it better.


const csvToArray = (csv) => {
 const array = csv.split('n').map(row => row.split(','));
 return array;
}

const fileToCSVArray = (file, callback) => {
 const reader = new FileReader();

 reader.onload = function() {
 const array = csvToArray(reader.result);
 callback(array);
 }

 reader.readAsText(file);
}

How it works

This code works by reading the CSV file, splitting it into lines, and then splitting each line into individual elements to form an array, using JavaScript’s FileReader() and string manipulation methods.

Here’s step-by-step explanation:

  • We define csvToArray function. This function takes a string csv as an argument, which is expected to contain the entire CSV file content. It splits this string into lines using n as the delimiter, creating an array. It then uses map to transform each line (row) separately, splitting each line into array elements using , as the delimiter.
  • We define fileToCSVArray function. This function takes a file object and a callback function as arguments. Within this function, we create a new FileReader object
  • We specify a function to be executed when the FileReader has successfully finished reading the file via the reader.onload event. This function converts the content of the file into an array using our previously defined csvToArray function, and then it calls the callback function with this array as an argument.
  • We use reader.readAsText(file) to start reading the content of the specified file. When this process is complete, it triggers the onload event, and the specified function is executed.

#2 – By using the fetch() and response.text() methods

By using the fetch() and response.text() methods

This guide demonstrates how to convert a CSV file to an array in JavaScript using the fetch() method to retrieve the file and the response.text() method to read its content. The example provided will illustrate this process in a step-by-step manner.


async function csvToArray(url) {
 const response = await fetch(url);
 const csv = await response.text();
 const array = csv.split('n').map(row => row.split(','));
 return array;
}
csvToArray('http://example.com/myfile.csv').then(array => console.log(array));

How it works

The function csvToArray makes an HTTP request to fetch a CSV file from a specified URL and converts its content into a JavaScript array.

  • Step 1: The function csvToArray is called with the URL of the CSV file as a parameter.
  • Step 2: The fetch() function is used to make an HTTP request to the given URL, which returns a Promise. Using await, the function waits for the Promise to resolve to a Response object.
  • Step 3: The response.text() method reads the Response object as text, and again, await is used to wait for the Promise to resolve to the CSV text.
  • Step 4: The CSV text is split into an array of lines using the split(‘n’) method, and then each line is split into an array of fields using map() method and split(‘,’). This results in a two-dimensional array representing the CSV file.
  • Step 5: The array is returned and then logged out to the console for demonstration.

#3 – By using the Papa Parse library

By using the Papa Parse library

We will use Papa Parse, a powerful and flexible library to parse CSV data in JavaScript, to convert CSV data to an array. We’ll utilize the parse method from Papa Parse, which will parse our CSV data and return an object that includes the parsed data as an array.


let csvData = 'Column1,Column2,Column3nValue1,Value2,Value3nValue4,Value5,Value6';
let parsedData = Papa.parse(csvData, {
 header: true,
 dynamicTyping: true,
 skipEmptyLines: true,
 complete: function(results) {
 console.log(results.data);
 }
});

How it works

The Papa.parse() function reads the CSV data, and converts it into JavaScript data structures, in this case an array of objects. The complete callback is intended to handle the parsed data after parsing is done.

  • Step 1: We provide CSV data as a string to be parsed.
  • Step 2: We provide configuration options to the Papa.parse() function.
    • The header option, when set to true, treats the first row of the CSV as the header and each parsed data becomes an object where the keys are the header names.
    • The dynamicTyping option, when set to true, will automatically convert the values to their actual types, for instance, from string ‘1’ to number 1.
    • The skipEmptyLines option, when set to true, will skip the empty lines in the CSV data.
    • The complete option is a callback function that gets called when parsing is complete. The parsed data can be accessed in this function.
  • Step 3: We parse the CSV data using Papa.parse() function and print the parsed data on the console inside the complete callback function.

Related:

In conclusion, mastering JavaScript’s array conversion from CSV files is a practical and necessary skill for dealing with data. By understanding how to apply methods like ‘split’ and ‘map’, we can turn complex CSV data into manageable JavaScript arrays with ease.

This skill not only enables us to manipulate data effectively but also opens up the possibility of working with larger datasets. With practice, we’ll be able to handle complex tasks and make our data more dynamic and interactive.

Leave a Reply

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