The task is to convert an integer array to a string array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript.
Approaches to convert Integer array to String array:
- using JavaScript array.map() and toString() methods
- using JavaScript Array.join() and split() methods
- using JavaScript Array.forEach() and String constructor
Approach 1: using JavaScript array.map() and toString() methods
In this approach, we use the .toString() method on every element of the array with the help of the .map() method.
Example: This example uses the approach discussed above.
let Arr = [1, 4, 56, 43, 67, 98]; function gfg_Run() {
let strArr = Arr.map( function (e) {
return e.toString()
});
console.log( "Array - " + strArr +
"\ntypeof(Array[0]) - " + typeof (strArr[0]));
} gfg_Run(); |
Array - 1,4,56,43,67,98 typeof(Array[0]) - string
Approach 2: Using JavaScript Array.join() and split() methods
In this approach, we use the join() method which joins the array and returns it as a string. Then split() method splits the string on “, ” returned by the join() method.
Example: This example uses the approach discussed above.
let Arr = [1, 4, 56, 43, 67, 98]; function gfg_Run() {
let strArr = Arr.join().split( ', ' );
console.log( "Array - " + strArr +
"\ntypeof(Array[0]) - " + typeof (strArr[0]));
} gfg_Run(); |
Array - 1,4,56,43,67,98 typeof(Array[0]) - string
Approach 3: Using JavaScript Array.forEach() and String constructor
In this approach, we will use JavaScript Array.forEach() to iterate the array and use String constructor to convert them into string type.
Example:
This example uses the approach discussed above.
const Arr = [1, 2, 3, 4, 5]; const strArr = []; Arr.forEach( function (num) {
strArr.push(String(num));
}); console.log( "Array - " + strArr +
"\ntypeof(Array[0]) - "
+ typeof strArr[0]
); |
Array - 1,2,3,4,5 typeof(Array[0]) - string