How to usearr.reduce() Method in Javascript
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.
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
JavaScript Program to Convert an Array into a String
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
Table of Content
- Approach 1: Using arr.join() Method
- Approach 2: Using arr.toString() Method
- Approach 3: Using JSON.stringify() Method
- Approach 4: Using arr.reduce() Method
- Approach 5: Using a for loop
- Approach 6: Using Array.prototype.map()
So we will see all of the above states approaches with its implementation.