How to convert Integer array to String array using JavaScript ?
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:
Table of Content
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();
Output
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();
Output
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]
);
Output
Array - 1,2,3,4,5 typeof(Array[0]) - string
Approach 4: Using Array.from() Method with a Mapping Function
In this approach, we use the Array.from() method, which creates a new array instance from an array-like or iterable object. We pass a mapping function as the second argument to convert each element to a string.
Example:
const integerArray = [10, 20, 30, 40, 50];
const stringArray = Array.from(integerArray, num => num.toString());
console.log("Array - " + stringArray + "\ntypeof(Array[0]) - " + typeof stringArray[0]);
Output
Array - 10,20,30,40,50 typeof(Array[0]) - string