Open In App

Convert Array to String in JavaScript

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use different separators based on your needs.

Prerequisites

These are the following approaches to convert an array to a string in JavaScript:

Using the JavaScript toString() method

The array.toString() method converts the array elements to strings and then concatenates them with commas as a separator. This method is generally preferred when we don't need any customization with the separators and formatting.

Syntax:

array.toString()

Example: The below mentioned code describes the approach along with an example of considering a sample array.

JavaScript
const array = [ 1, 2, 3, 4, 5 ];
const str = array.toString();
console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));

Output
Resultant string:  1,2,3,4,5
Type of resultant string:  string

Using JavaScript join() method

The array.join(separator) method is used to join the elements of an array using the 'separator' operator provided. If no separator is provided then it uses the default separator as comma. This method is very useful when one needs to apply custom separator.

Syntax:

array.join(separator)

Example: In this approach we would be illustrating the usage of join method to convert an array elements to string using different separators.

JavaScript
const array = ['a', 'b', 'c'];

const str1 = array.join();    // Default separator (comma)
console.log('Using default separator: ', str1);

const str2 = array.join(' '); // Space as separator
console.log('Using space as a separator: ', str2);

const str3 = array.join('-'); // Hyphen as separator
console.log('Using hyphen as a separator: ',str3);

console.log('Type of str1: ', typeof(str1), ', Type of str2: ', 
typeof(str2), ', Type of str3: ', typeof(str3));

Output
Using default separator:  a,b,c
Using space as a separator:  a b c
Using hyphen as a separator:  a-b-c
Type of str1:  string , Type of str2:  string , Type of str3:  string

Using JavaScript JSON.stringify() method

The JSON.stringify() method converts an array including even the nested arrays and objects to a JSON string. This method is very useful especially in the case while preserving the structure of the complex data or even arrays over the network.

Syntax:

JSON.stringify(array)

Example: The code converts the array to a JSON string using JSON.stringify().

JavaScript
const array = [1, 'Hello', true, { key: 'value' }];
const str = JSON.stringify(array);
console.log('The resulted string is: ',str);
console.log("The type of generate 'str' is: ",typeof(str)); 

Output
The resulted string is:  [1,"Hello",true,{"key":"value"}]
The type of generate 'str' is:  string

Using JavaScript String() method

  • The String() method converts the array elements to string and then concatenates them with commas as a separator.
  • This method is generally preferred when we don't need any customization with the separators and formatting.
  • This method is similar to array.toString() method but the major difference is that array.toString() will show an error message
  • if the array value if null but the String(array) method will display a message reading 'null' and won't throw any error.
  • So, it depends on the user to use the method according to their needs.

Syntax:

String(array)

Example: The code converts both array (which is null) and array1 to strings using String().

JavaScript
const array = null;
const array1 = [1, 2, 3, 4, 5]

let str = String(array);
console.log('Resultant string (null value of array): ', str);
console.log('Type of resultant string (null value of array): ', typeof(str));

str = String(array1);
console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));

Output
Resultant string (null value of array):  null
Type of resultant string (null value of array):  string
Resultant string:  1,2,3,4,5
Type of resultant string:  string

Using JavaScript reduce() method

The reduce() method in general executes the reducer function for each and every element of an array and finally returns an accumulated value as a resulting value. It skips the array elements that are empty and it does not modify the original array which makes this method useful in such case. Here, we modified it and made it iterate over all the array elements and accumulate the result in an accumulator.

Syntax:

array.reduce(callback(accumulator, currentValue), initialValue)

Example: The code uses reduce to concatenate the elements of array into a string, separated by ", ".

JavaScript
const array = [1, 2, 3, 4, 5];

// Instead of ", " one can use any separator
const str = array.reduce((acc, curr) => acc + ", " + curr);

console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));

Output
Resultant string:  1, 2, 3, 4, 5
Type of resultant string:  string

Using JavaScript map() with join() method

  • The map() method generates an entirely new array by applying the given function for each and every element of an array.
  • It does not modify the original array instead creates a new array to store after making all the necessary operations from the function given.
  • One most important feature of map() method is that it skips the empty element i.e. it skips the execution of the callback function when it finds an empty element and it focuses only on the non-empty values.
  • Here, in this approach we transform each and every element using 'map()' method and then join it using 'join()' method.
  • This method is very useful when you need to apply some transformation before converting to string.

Syntax:

array.map(callback(element)).join(separator)

Example: The code converts each element of the array to a string using map and then joins them with different separators (default comma, space, and hyphen).

JavaScript
const array = [1, 2, 3, 4, 5];

// Default separator (comma)
const str1 = array.map(num => `${num}`).join();    

console.log('Using default separator: ', str1);
// Space as separator
const str2 = array.map(num => `${num}`).join(' '); 
console.log('Using space as a separator: ', str2);

// Hyphen as separator
const str3 = array.map(num => `${num}`).join('-'); 
console.log('Using hyphen as a separator: ',str3);

console.log('Type of str1: ', typeof(str1), ',
Type of str2: ', typeof(str2), ', Type of str3: ', typeof(str3));

Output
Using default separator:  1,2,3,4,5
Using space as a separator:  1 2 3 4 5
Using hyphen as a separator:  1-2-3-4-5
Type of str1:  string , Type of str2:  string , Type of str3:  string

Using JavaScript foreach() method with string concatenation

  • The foreach() method of JavaScript calls a callback function and performs operations specified on each and every element.
  • Basically, it neither creates new array nor modifies the original array. It basically performs operations on each and every element.
  • Here, in this approach the foreach() method iterates over each and every element and manually concatenates them into the string.
  • This type of method is very useful when one needs to build a string manually with the specific logic for each and every element.

Syntax:

array.forEach(callback(element))

Example: The code concatenates the elements of array into a single string str using forEach, and then logs the resultant string and its type.

JavaScript
const array = [1, 2, 3, 4, 5];
let str = '';
array.forEach(num => {
  str += num;
});

console.log('Resultant string: ', str);
console.log('Type of resultant string: ', typeof(str));

Output
Resultant string:  12345
Type of resultant string:  string

Using JavaScript flat() with join()

  • The flat() method in JavaScript creates a new array with all the elements of the original sub array and joins them up to a certain depth.
  • Depth is specified as a parameter while calling flat() method. If no depth is mentioned then it by default considers the value of depth as 1.
  • Here, in this approach the flat() method flattens the nested or normal array and then using the join() method it joins all of them with the separator mentioned as a parameter.

Syntax:

 array.flat().join(separator)

Example: The code flattens the `array` and joins the elements into strings using different separators (default comma, space, and hyphen), then logs the resulting strings and their types.

JavaScript
const array = [1, 2, [3, 4], 5];

 // Default separator (comma)
const str1 = array.flat().join();   
console.log('Using default separator: ', str1);

// Space as separator
const str2 = array.flat().join(' '); 
console.log('Using space as a separator: ', str2);

// Hyphen as separator
const str3 = array.flat().join('-'); 
console.log('Using hyphen as a separator: ',str3);

console.log('Type of str1: ', typeof(str1), ', Type of str2: ', 
typeof(str2), ', Type of str3: ', typeof(str3));

Output
Using default separator:  1,2,3,4,5
Using space as a separator:  1 2 3 4 5
Using hyphen as a separator:  1-2-3-4-5
Type of str1:  string , Type of str2:  string , Type of str3:  string

Next Article

Similar Reads