OneCompiler

Convert an Array to CSV in Javascript

1062


Convert an Array to CSV in Javascript

Array

An Array is a collection of elements enclosed under a single name

Example:

var languages = [ "C", "C++", "Python"];

CSV

A CSV (comma separated values) is a Text file that contains list of data separated by commas

Example:

C, C++, Python

Array to CSV

To Convert an array to a CSV we first convert the array to a string then we use valueOf()Method

var languages = ["C", "C++", "Python"];
var strings = languages.toString().valueOf();
console.log(strings) // C,C++,Python

The valueOf() Method converts an array to comma separated values, Now what if you want the elements of array to be separated by any other symbol?
To do so, we can use the join() Method

var languages = ["C", "C++", "Python"];
var strings = languages.join("^");
console.log(strings) // C^C++^Python

That's it guys, a short yet effective technique you can use