22 Sept 2015

How to Convert JavaScript Array to CSV

Converting JavaScript Array to CSV

==============================

First one goes like this. You have a javascript array of strings (or numbers) and you want to convert it to comma separated values (csv). We’ll below is the code snippet:
Reference: Array to CSV in JavaScript
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
 
var str = fruits.valueOf();
 
//print str: apple,peaches,oranges,mangoes
The valueOf() method will convert an array in javascript to a comma separated string.
Now what if you want to use pipe (|) as delimeter instead of comma. You can convert a js array into a delimeted string using join() method. See below:
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
 
var str = fruits.join("|");
 
//print str: apple|peaches|oranges|mangoes
The join() method will convert the array into a pipe separated string.

Share:

0 comments:

Post a Comment