Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a CSV File Into a 2D Array

How can i convert the data inside an CSV file to a 2d array?

array[row][column]

I already have an upload script that will display all the data inside a CSV file.

Little snippet of my code, here's the full code: http://jsfiddle.net/Meesz/wj6q7c30/

reader.onload = function (e) {
  var table = document.createElement("table");
  var rows = e.target.result.split("\n");
  for (var i = 0; i < rows.length; i++) {
    var row = table.insertRow(-1);
    var cells = rows[i].split(",");
    for (var j = 0; j < cells.length; j++) {
        var cell = row.insertCell(-1);
        cell.innerHTML = cells[j];
    }
  }
  var dvCSV = document.getElementById("dvCSV");
  dvCSV.innerHTML = "";
  dvCSV.appendChild(table);
}
like image 212
Mvz Avatar asked Oct 15 '15 18:10

Mvz


People also ask

How do I convert a CSV file to an array in Python?

You can convert a CSV file to a NumPy array simply by calling np. loadtxt() with two arguments: the filename and the delimiter string. For example, the expression np. loadtxt('my_file.


1 Answers

Real answer: Use Papa Parse . Save yourself the hassle of escaped/quoted fields, fields with delimiters in them, variations in the CSV format, etc...

The "do it yourself" way: csvStr.split("\n").map(function(row){return row.split(",");})

like image 156
Fabio Beltramini Avatar answered Sep 19 '22 00:09

Fabio Beltramini