Open In App

Create a comma separated list from an array in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we will see how to convert an array into a comma-separated list using JavaScript. To do that, we are going to use a few of the most preferred methods.

Methods to Create Comma Separated List from an Array:

Method 1: Array join() method

This method joins the elements of the array to form a string and returns the new string. The elements of the array will be separated by a specified separator. If not specified, the Default separator comma (, ) is used. 

Syntax:

array.join(separator)

Parameters:

  • separator: This parameter is optional. It specifies the separator to be used. If not used, a Separated Comma(, ) is used.

Example: This example joins the element of the array by the join() method using a comma(, )

Javascript




// Input array
let arr = ["GFG1", "GFG2", "GFG3"];
 
// Function to create and
// display comma separated list
function gfg_Run() {
    console.log("Comma Separates List: " + arr.join(", "));
}
 
gfg_Run();


Output

Comma Separates List: GFG1, GFG2, GFG3

Method 2: Array toString() method

This method converts an array into a String and returns the new string. 

Syntax:

array.toString()

Return value:

It returns a string that represents the values of the array, separated by a comma.

Example: This example uses the toString() method to convert an array into a comma-separated list. using Array literal

Javascript




// Input array
let arr = ["GFG1", "GFG2", "GFG3"];
 
// Function to create and
// display comma separated list
function gfg_Run() {
    console.log("Comma Separated List: " + arr.toString());
}
 
gfg_Run();


Output

Comma Separated List: GFG1,GFG2,GFG3

Method 3: Using Array literals

It is the list of expressions containing array elements separated with commas enclosed with square brackets.

Example: This example uses the normal array name and does the same work. 

Javascript




// Array litral declaration
let arr = ["GFG1", "GFG2", "GFG3"];
 
// Function to display
// comma separated list
function gfg_Run() {
    console.log("Comma Separated List: " + arr);
}
 
gfg_Run();


Output

Comma Separated List: GFG1,GFG2,GFG3

Method 4: Using Lodash _.join() method

In this appraoch, we are using Lodash _.join() method that return the list of given array with “,” separation.

Example: This example shows the use of Lodash _.join() method.

Javascript




// Requiring the lodash library
let _ = require("lodash");
 
// Original array to be joined
let array = [1, 2, 3, 4, 5, 6];
 
let newArray = _.join(array);
// Printing newArray
console.log("After Join: " + newArray);


Output:

After Join: 1,2,3,4,5,6


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