Open In App

JavaScript Program to Convert an Array into a String

Last Updated : 25 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We have been given an array as an input that consists of various elements and our task is to convert this array of elements into a string by using JavaScript. Below we have added the examples for better understanding:

Example:

Input: arr= [1,2,3,4,5,6]
Output: 1,2,3,4,5,6

So we will see all of the above states approaches with its implementation.

Approach 1: Using arr.join() Method

The join method in JavaScript is used to join the elements of an array into the string. Here, we can specify the separator or else by default it will take comma as the default separator.

Syntax:

array.join(optional_separator)

Example: In this example, we have used the default separator to show the converted array elements into string.

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let str = arr.join(); 
console.log(str);


Output

1,2,3,4,5,6,7,8,9,10

Approach 2: Using arr.toString() Method

The toString method in JavaScript is used to convert each element of the array to a string and concatenate them, by separating the elements using the comma.

Syntax:

array.toString()

Example: In this example, we are using the toString method to convert the array elements into the string.

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let str = arr.toString(); 
console.log(str);


Output

1,2,3,4,5,6,7,8,9,10

Approach 3: Using JSON.stringify() Method

The JSON.stringify() method in JavaScript is used to convert the entire array consisting of nested arrays into the JSON-formatted string.

Syntax:

JSON.stringify(array)

Example: In this example, we will be using the JSON.stringify() method to convert array element into string.

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let str = JSON.stringify(arr).slice(1, -1);
console.log(str);


Output

1,2,3,4,5,6,7,8,9,10

Approach 4: Using arr.reduce() Method

The arr.reduce method in JavaScript concatenates the elements of the array into a single string starting from the empty string as the initialValue of the accumulator.

Syntax:

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

Example: In this example, we are using the arr.reduce() method to convert array into string.

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let str = 
    arr.reduce((myString, values, myArr) => {
  if (myArr === 0) {
    return `${values}`;
  } else {
    return `${myString},${values}`;
  }
}, '');
console.log(str);


Output

1,2,3,4,5,6,7,8,9,10


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads