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 toString() function
<script> var array = [ "geeks" , "4" , "geeks" ]; var csv = array.toString(); document.write(csv); </script> |
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() function
<script> var array = [ "geeks" , "4" , "geeks" ]; var csv = array.valueOf(); alert(csv); </script> |
Output:
geeks,4,geeks
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 in toString() and valueOf(). Even if we try with different data types like number, strings etc it would give the same result.
Method 3: using join() function
<script> var array = [ "geeks" , "4" , "geeks" ]; var csv = array.join(); document.write(csv); </script> |
Output:
geeks,4,geeks
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() method and specify the separator. For example:
<script> var array = [ "geeks" , "4" , "geeks" ]; var csv = array.join( '|' ); document.write(csv); </script> |
Output:
geeks|4|geeks
Converting CSVs into Arrays: Using split() function
Now let us see how we can convert a string with commas separated values into an Array.
<script> var csv = "geeks, 4, geeks" var array = csv.split( ", " ); document.write(array[0] + '<br>' ); document.write(array[1] + '<br>' ); document.write(array[2]); </script> |
Output:
geeks 4 geeks
Thus split() method of String comes 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.