In the previous article, I mentioned how to Convert CSV to JSON using Javascript but in this article, I have mentioned how we can parse CSV data into array using Javascript.
Using Custom function
In this method, we will read CSV file and using our custom function, we will convert CSV data into the array.
So for example, we have a CSV file below
Id,Country,Price,OrderQuantity
1,India,10.00,4
2,Australia, 5.00,10
3,Brazil, 10.00,5
4,China,5.50,5
5,Nepal,20.20,10
We will load the CSV file and then read CSV each line and convert them into array using below JS
myReader.onload = function(e) {
//get file contents, split them by line
let data = myReader.result.split("\r\n");
for (let i in data) {
//loop each row split them by "," and save it in array
data[i] = data[i].split(",");
}
//print array
console.log(data);
}
So the full code to read CSV and convert it into Array would be as below
function processFile() {
var fileSize = 0;
//get file
var theFile = document.getElementById("myFile");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
//check if file is CSV
if (regex.test(theFile.value.toLowerCase())) {
//check if browser support FileReader
if (typeof (FileReader) != "undefined") {
//create html5 file reader object
var myReader = new FileReader();
// call filereader. onload function
myReader.onload = function(e) {
//get file contents, split them by line
let data = myReader.result.split("\r\n");
for (let i in data) {
//loop each row split them by "," and save it in array
data[i] = data[i].split(",");
}
//print array
console.log(data);
}
//call file reader onload
myReader.readAsText(theFile.files[0]);
}
else {
alert("This browser does not support HTML5.");
}
}
else {
alert("Please upload a valid CSV file.");
}
return false;
}
Considering HTML to browse/load CSV file
Select a file: <input type="file" id="myFile">
<button onclick='processFile()'>Process</button>
<table id="myTable"></table>
Output:
[
["Id", "Country", "Price", "OrderQuantity"],
["1", "India", "10.00", "4"],
["2", "Australia", " 5.00", "10"],
["3", "Brazil", " 10.00", "5"],
["4", "China", "5.50", "5"],
["5", "Nepal", "20.20", "10"]
]
here is the fiddle for demo
Using jQuery CSV Library
Another way to convert CSV into Array would be to use jQuery library https://github.com/evanplaice/jquery-csv/, which will allow you to pass CSV file and returns array using the below function
$.csv.toArrays(csv);
Above method is Used to parse a single line of CSV data into an array of values.
You can check it's sample here
http://evanplaice.github.io/jquery-csv/examples/to-array.html
It is an easy to use plugin, but I would like to suggest to use Pure Javascript based method, as it is not dependent on another library plus you will not require jQuery.
You may also like to read:
RGB to Hex or Hex to RBG using Javascript