Build an Array from csv file

How do I build an array from csv file . I have seen a lot of parse plugins like jquery-csv and papa parser but am unable to understand what code should I use being a beginner.

What I need is an array like

var myArray = ["abc", "def", "ghi"];

and these values abc, def, ghi should come from a file named xyz.csv

I have tried something on codepen

Can someone guide ?

Are you wanting to do this client-side or server-side?

For node you might check out fast-csv, which is very easy to use; e.g. you can directly parse from a file by specifying the path like

var csv = require('fast-csv');

csv.fromPath('xyz.csv')
  .on('data', function(data) {

    // `data` is an array containing the values
    // of the current line in the file
    console.log(data);
  })
  .on('end', function() {
    console.log('Parsing complete!');
  });

I’m not familiar with such tools for the browser, but the parsing itself would basically be a simple line.split(delimiter) … like e.g.

function parseCSV(file, delimiter, callback) {
  var reader = new FileReader();

  // When the FileReader has loaded the file...
  reader.onload = function() {
  
    // Split the result to an array of lines
    var lines = this.result.split('\n');
    
    // Split the lines themselves by the specified
    // delimiter, such as a comma
    var result = lines.map(function(line) {
    	return line.split(delimiter);
    });
    
    // As the FileReader reads asynchronously,
    // we can't just return the result; instead,
    // we're passing it to a callback function
    callback(result);
  };
  
  // Read the file content as a single string
  reader.readAsText(file);
}

Here’s a fiddle.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.