How to parse CSV to Array in JavaScript? [SOLVED]


Written By - Olorunfemi Akinlua
Advertisement

Introduction

Comma-separated values (CSV) are important file types that store 2D data (row-by-column data). In JavaScript, we can process CSV files, convert them to strings, and convert them into a JavaScript array using JavaScript built-in methods.

This article will discuss the different approaches we can take to convert CSV to an array in JavaScript.

 

Method-1: Use split() method to convert CSV to Array

Before we go into detail about how to read CSV files in JavaScript, once we have processed the CSV data into a string format, we can make use of a method to convert the CSV-type string to an array.

The method is called .split(), and it takes a string argument that specifies the character or characters to use for separating the string into an array. The default character for .split() is whitespace. For a CSV file, the delimiter is typically a comma (,).

So, if you have a CSV file with data like this:

Name,Age,City

John,30,New York

Jane,40,Los Angeles

Mike,25,Paris

You can use the .split() method to convert it into an array using a code like this.

let data = `name,age,city\\

John,30,New York\\

Jane,40,London\\

Mike,25,Paris`;

let array = data.split("\\n").map(function (line) {
    return line.split(",");
});

console.log(array);

Output

[
  [ 'name', 'age', 'city' ],
  [ 'John', '30', 'New York' ],
  [ 'Jane', '40', 'London' ],
  [ 'Mike', '25', 'Paris' ]
]

The code splits the string first by the \\n (newline character) to have each line, and then uses the map function to work on each line to split each line by the CSV delimiter - ,.

Advertisement

We can create a function based on the code

function csvToArray(str, delimiter = ",") {
    let array = str.split("\\r\\n").map(function (line) {
        return line.split(delimiter);
    });

    return array;
}

As you can see, this method can be very useful for converting CSV data into a format that can be easily manipulated with JavaScript.

 

Method-2: Use FileReader method

If we want to run the JavaScript within the browser, we can make use of the FileReader object. It allows us to read file contents based on File or Blob objects.

So, we create a simple HTML form that takes the CSV file and creates an submit event listener that triggers the FileReader object and the csvToArray method we have created.

<!DOCTYPE html>
<html lang="en">
    <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" />
        <title>Document</title>
    </head>
    <body>
        <form id="form">
            <input type="file" id="file" accept=".csv" />
            <br />
            <input type="submit" value="Submit" />
        </form>
        <script>
            const myForm = document.getElementById("form");
            const csvFile = document.getElementById("file");

            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;
                    const array = csvToArray(text);
                    document.write(JSON.stringify(array));
                };

                reader.readAsText(input);

                function csvToArray(str, delimiter = ",") {
                    let array = str.split("\\r\\n").map(function (line) {
                        return line.split(delimiter);
                    });

                    return array;
                }
            });
        </script>
    </body>
</html>

The output within your browser should look like the below

[["name","age","city"],["John","30","New York"],["Jane","40","London"],["Mike","25","Paris"],["Femi","22","Lagos"],["Jacob","24","Kampala"],[""]]

 

Method-3: Use csv-parse method

If we want to convert CSV to an array locally, we can use a Node.js package called csv-parse. It helps convert CSV text into arrays or objects and makes use of the stream.Transform API.

To install the csv-parse package, we can the npm command

npm i csv-parse

To read the CSV, we need the createReadStream() function where we pass the path to the CSV file we want to process and convert. Then, we use the pipe function to connect the data stream to the parse function.

Advertisement
const fs = require("fs");
const { parse } = require("csv-parse");

fs.createReadStream("./data.csv")
    .pipe(parse({ delimiter: ",", from_line: 2 }))
    .on("data", function (row) {
        console.log(row);
    })
    .on("error", function (error) {
        console.log(error.message);
    })
    .on("end", function () {
        console.log("Done");
    });

Output

[ 'John', '30', 'New York' ]
[ 'Jane', '40', 'London' ]
[ 'Mike', '25', 'Paris' ]
[ 'Femi', '22', 'Lagos' ]
[ 'Jacob', '24', 'Kampala' ]
Done

 

Summary

Depending on the environment we want to achieve the operation of converting CSV files to an array, we can make use of the FileReader object or the cvs-parse package. Both can achieve the goal with ease.

 

References

FileReader - Web APIs | MDN (mozilla.org)
String.prototype.split() - JavaScript | MDN (mozilla.org)
csv-parse - npm (npmjs.com)

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment