1

I have a very simple array that I'd like to export to CSV:

var uniqueCounties = ["555","123","345"];

I have tried using methods found online but I have been getting various errors, and all the methods online deal with nested arrays.

My function at the moment is converting to a string. I was hoping it would simplify the process but I'm still now sure how to progress:

function download_csv() {
        var csv = uniqueCounties.toString();
        console.log(csv);
    }

I was originally trying this method:

uniqueCounties.forEach(function(infoArray, index){

   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;

});

But kept getting the error infoArray.join is not a function.

sparta93
  • 3,376
  • 4
  • 25
  • 57
Matthew Snell
  • 747
  • 2
  • 8
  • 24

2 Answers2

1

If you have a 2d array of strings (or anything that you are ok with toString-ing) for example:

const input = [
  ["555","123","345"],
  [1, 2, 3],
  [true, false, "foo"]
]

Then you can do something like this:

function toCsv(input) {
  return input.map(row => row.join(',')).join('\n')
}

const csvString = toCsv(input)

Resulting in this string:

555,123,345
1,2,3
true,false,foo

If you just want to convert a single 1d array to csv, like in the example then:

const uniqueCounties = ["555","123","345"]

// If you want each value as a column
const csvAsSingleRow = uniqueCounties.join(',')

// If you want each value as a row
const csvAsSingleColumn = uniqueCounties.join('\n') 

This gets more and more complicated if you want to include escaping, etc... In that case I'd recommend looking for a library that does this well.

Balázs Édes
  • 12,013
  • 4
  • 45
  • 79
  • Thanks for the reply! I went with the `csvAsSingleRow` approach and had it `console.log` the output. Would it be difficult from here to download this as a CSV file? – Matthew Snell Mar 30 '17 at 17:03
  • Not sure what do you mean by download. Do you run this in the browser or node? – Balázs Édes Mar 30 '17 at 18:07
  • It's ran in the browser. The idea is someone can map counties (hence the uniqueCounties variable). And then export the selection to a file on their computer. – Matthew Snell Mar 30 '17 at 18:09
  • See this answer for that http://stackoverflow.com/a/14966131/1126273 You have to either encode it as an URI along with the information of what file type it is and call `window.open` with the string, or create a link. The answer explains both nicely. – Balázs Édes Mar 31 '17 at 07:32
1

This post has the same question as yours. It has an accepted answer that has JS code to allow downloading the CSV as well.

Hope this helps.

Export javascript data to CSV file without server interaction

Community
  • 1
  • 1
dev
  • 74
  • 4