samjaninf
9/26/2018 - 6:36 PM

Convert tabular text (csv, tsv, etc.) to javascript array

Convert tabular text (csv, tsv, etc.) to javascript array

var to_array = function(text, delimeter, has_header, header_size) {
  var lines = text.split('\n');
  var columns = has_header ? lines[header_size - 1].split(delimeter) : null;
  var rows = [];

  for (var i=header_size; i<lines.length; i++) {
    var array = lines[i].split(delimeter);
    var row = {};

    for (var j in array) {
      row[has_header ? columns[j] : j] = array[j]
    }
    
    rows.push(row);
  }

  return rows;
}