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.
- Using the toString() method
- Using valueof() Method
- Using the join() function
- Using the split() function
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 = [ "neveropen" , "4" , "neveropen" ]; let csv = array.toString(); console.log(csv); |
neveropen,4,neveropen
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 = [ "neveropen" , "4" , "neveropen" ]; let csv = array.valueOf(); console.log(csv); |
[ 'neveropen', '4', 'neveropen' ]
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 = [ "neveropen" , "4" , "neveropen" ]; let csv = array.join(); console.log(csv); |
neveropen,4,neveropen
Example:
javascript
let array = [ "neveropen" , "4" , "neveropen" ]; let csv = array.join( '|' ); console.log(csv); |
neveropen|4|neveropen
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 = "neveropen, 4, neveropen" let array = csv.split( ", " ); console.log(array[0]); console.log(array[1]); console.log(array[2]); |
neveropen 4 neveropen
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.