Write Array to CSV in JavaScript

Using toString() method

To write array to CSV in JavaScript:

  • Declare an array with some elements in it.
  • Use the toString() method. This method will convert the array into the CSV(Comma-Separated Value).
  • Finally, console the value to see the result.

Follow the below program:

Output:

Using join() method

To write array to CSV in JavaScript:

  • Declare an array that consists of some elements
  • Use the join() method and pass the symbol as an argument that will be used in joining the elements. This method returns the result in the string form.
  • Finally, console it to see the result.

Follow the below program:

Output:

We used comma(,) to join the array elements. In your case, you can use other symbols also.

Our purpose is to write CSV(Comma-Separated Value) from an Array in JavaScript.

Using valueOf() method

To write array to CSV in JavaScript:

  • The valueOf() method works exactly as the toString() method. You can follow the steps that are followed while using the toString() method. All you need to do is to use the valueOf() instead of toString().

Follow the below program:

Output:

Write Array of Objects to CSV

To write Array of Objects to CSV:

  • Declare an array that consists of some objects.
  • Define the column headers and then use the spread(…) operator as well as the map() function to separate the key-value pairs from the array.
  • Finally, use another map() function and join() method to separate the values with a comma(,)
  • Console.log() them to see the output.

Follow the below program:

Output:

We used the spread(...) operator to extract the key-value pair and used the map() function to convert the Object data into the array.

Now, we get the element into an array form. We used the mapping function and the join() method in this array. This will join the array elements with a comma(,) and convert them into the string.

Another join() method is used to separate the strings into a new line.

Finally, We consoled arrayOfObject as well as used the typeOf() method. It shows that it is an Object.

We consoled arrayOfObjectToCSV and also used the typeOf() method here. It shows String.

That’s all about how to write array to CSV in JavaScript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *