How to convert JavaScript Arrays to CSV (Comma Separated Values)

Let’s see a small code snippet in Javascript that converts JS arrays in Comma separated values. It is also possible to convert an array to delimited text where one can choose the separator.

var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = fruits.toString(); //print str: apple, peaches, oranges, mangoes
Code language: JavaScript (javascript)

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. That’s simple. Javascript Array also has method valueOf() that does the same thing.

var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = fruits.valueOf(); //print str: apple,peaches,oranges,mangoes
Code language: JavaScript (javascript)

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(). Try with different data types like number, strings etc it would give the same result. Also sometimes one wants to create delimited string from an array. Lets say pipe (|) separated string!. In such cases Arrays join() method comes quite handy. 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 argument to join() method and specify the separator. For example:

var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = fruits.join("|"); //print str: apple|peaches|oranges|mangoes
Code language: JavaScript (javascript)

How to convert CSV to Array in JavaScript

Let us see how to convert a string with commas in it into an Array. Consider following case:

var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = "apple, peaches, oranges, mangoes"; var fruitsArray = str.split(","); //print fruitsArray[0]: apple
Code language: JavaScript (javascript)

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. Check the sytax of split() method.

string.split(separator,limit)
Code language: JavaScript (javascript)
  • separator (Optional). Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item
  • limit (Optional). An integer that specifies the number of splits, items after the split limit will not be included in the array

Note: If an empty string (“”) is used as the separator, the string is split between each character. Thus:

var str="How are you doing today?"; var n=str.split("");
Code language: JavaScript (javascript)

The result of n will be an array with the values:

H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?

View Comments

  • Hello: I am hoping someone can answer this question. It sound as though it may not be possible but---what I would like to do is take a variable from a form question and, if there are more than one selection among all the variables, echo the selections separated by commas, "and" or "or" or both. e.g.

    [code language="html"]
    <input type="checkbox" name="fruit[]" value="apple" id="fruit_a_1" />
    <input type="checkbox" name="fruit[]" value="grape" id="fruit_b_2" />
    <input type="checkbox" name="fruit[]" value="orange" id="fruit_c_3" />
    [/code]

    If two of the choices were selected, I would like the screen output to look like this:

    apple and orange
    and if three of the choices were selected, I would like to see this:
    apple, grape and orange

    I've been able to add commas but don't know how to incorporate the "and" or "or" using php.

    Can you do this with javascript or php?

    Thanks for any help you can provide!

    • You can do this in both PHP as well as JS. See below code for JS:
      [code language="js"]
      var ar = ['apple', 'peaches', 'mangoes'];
      var output;
      if(ar.length == 2)
      output = ar.join(" and ");
      else if(ar.length > 2) {
      output = ar.slice(0, ar.length-1) + " and " + ar[ar.length-1];
      }
      //print output;
      [/code]

      Check demo: http://jsfiddle.net/LQHWF/1/

  • This does not convert an array to CSV.
    CSV is a special format that handles escaping of elements that may include commas etc.
    This can not be done with a simple toString() call but needs to take into account all the exception cases involved in the full CSV specification

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago