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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
Not sure what do you mean by download. Do you run this in the browser or node?
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.
See this answer for that 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.