Open In App

Converting JavaScript Arrays into CSVs and Vice-Versa

Improve
Improve
Like Article
Like
Save
Share
Report

Converting Arrays into CSVs: Given an array in JavaScript and the task is to obtain the CSVs or the Comma Separated Values from it. Now, JavaScript being a versatile language provides multiple ways to achieve the task.

Some of them are listed below.

Method 1: Using the toString() method

In this method, we will use the toString() method o obtain the CSVs or the Comma Separated Values.

javascript




let array = ["geeks", "4", "geeks"];
let csv = array.toString();
console.log(csv);


Output

geeks,4,geeks



The toString() method converts an array into a String and returns the result. The returned string will separate the elements in the array with commas. 

Method 2: Using valueof() Method

The valueOf() method returns the primitive value of an array. Again the returned string will separate the elements in the array with commas. There is no difference between toString() and valueOf(). Even if we try with different data types like numbers, strings, etc it would give the same result.

Example:

javascript




let array = ["geeks", "4", "geeks"];
let csv = array.valueOf();
console.log(csv);


Output

[ 'geeks', '4', 'geeks' ]



Method 3: Using the join() function

The join() method joins the elements of an array into a string and returns the string. By default, the join() method returns a comma (, ) separated value of the array. But you can give an argument to join the () method and specify the separator. 

Example:

javascript




let array = ["geeks", "4", "geeks"];
let csv = array.join();
console.log(csv);


Output

geeks,4,geeks



Example: 

javascript




let array = ["geeks", "4", "geeks"];
let csv = array.join('|');
console.log(csv);


Output

geeks|4|geeks



Method 4: Using the split() function

Converting CSVs into Arrays: Using the split() function Now let us see how we can convert a string with comma-separated values into an Array. 

javascript




let csv = "geeks, 4, geeks"
let array = csv.split(", ");
console.log(array[0]);
console.log(array[1]);
console.log(array[2]);


Output

geeks
4
geeks



Thus split() method of String comes in handy for this. It is used to split a string into an array of substrings and returns the new array. The split() method does not change the original string.



Last Updated : 17 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads