csv to array javascript code example

Example 1: javascript array to csv string

var colors = ["red", "blue", "green"];
var colorsString = colors.join(","); //"red,blue,green"

Example 2: CSV to 2D array javaescript

function csvToArray(csv, delimiter = ",", omitFirstRow = false) {
  console.log(csv.indexOf('\n'));
  return csv.slice(omitFirstRow ? csv.indexOf('\n')+1 : 0)
            .split("\n")
            .map((element) => element.split(delimiter));
}

let csv1 = "a,b\nc,d";
let csv2 = "a;b\nc;d";
let csv3 = "head1,head2\na,b\nc,d";

let result1 = csvToArray(csv1);
let result2 = csvToArray(csv2);
let result3 = csvToArray(csv3);

console.log(result1);
console.log(result2);
console.log(result3);

Example 3: js array to csv

const arrayToCSV = (arr, delimiter = ',') =>
  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');

Example 4: convert array to csv javascript

var objectToCSVRow = function(dataObject) {
    var dataArray = new Array;
    for (var o in dataObject) {
        var innerValue = dataObject[o]===null?'':dataObject[o].toString();
        var result = innerValue.replace(/"/g, '""');
        result = '"' + result + '"';
        dataArray.push(result);
    }
    return dataArray.join(' ') + '\r\n';
}

var exportToCSV = function(arrayOfObjects) {

    if (!arrayOfObjects.length) {
        return;
    }

    var csvContent = "data:text/csv;charset=utf-8,";

    // headers
    csvContent += objectToCSVRow(Object.keys(arrayOfObjects[0]));

    arrayOfObjects.forEach(function(item){
        csvContent += objectToCSVRow(item);
    }); 

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "customers.csv");
    document.body.appendChild(link); // Required for FF
    link.click();
    document.body.removeChild(link); 
}