How To Convert Array Of Numbers To Array Of Strings In JavaScript

Convert Array of Numbers to Array of Strings in JavaScript

Many methods will help you convert array of numbers to array of strings in JavaScript. In this article, I will show you how to use the join(), split(), map() functions, and forEach() loop to do that. Find out more details in this article below.

Convert array of numbers to array of strings in JavaScript

Using forEach() method

The idea of converting a numeric array to a string array is to convert each numeric element of the original numeric array into a string value carrier and push that element into a new string array. 

In JavaScript, the forEach() function is used to iterate through the elements of an array quickly, and the toString() method allows you to convert any number value to its string type.

Code sample:

let arrNum = [1, 4, 5, 2, 7, 8];
let arrStr = [];
 
// Iterate through each element, convert it to a string and push it into the new array
arrNum.forEach(element=>{
    arrStr.push(element.toString());
})
 
console.log(arrStr);

Output

(6) ['1', '4', '5', '2', '7', '8']

In the above example, we have used the push() method to add the number element that has been converted to a string into the new empty array so that when iterating through all the elements in the original number sequence, we get a new string array.

Using map() method

In addition to using the forEach() method to iterate each element, the map() method in Javascript is also used to iterate through the array elements. It allows processing the value of that element.

Code example:

let arrNum = [1, 4, 5, 2, 7, 8];
 
// Iterate through each element of the number array and convert it to a string
let arrStr = arrNum.map((element)=>{
    return String(element);
})
 
console.log(arrStr);

Output

(6) ['1', '4', '5', '2', '7', '8']

Using join() and split() method

Another idea to convert a numeric array to a string array is to use the join() function which will concatenate the elements of the array into a string, from which the numbers in the original array have been converted to strings. Then use the string.split() method to split the string into an array of string elements, like the following example.

Code sample:

let arrNum = [1, 4, 5, 2, 7, 8];
 
// Use join() function and split() function to convert
let arrStr = arrNum.join().split(',');
 
console.log(arrStr);
console.log(typeof arrStr[1]);

Output

(6) ['1', '4', '5', '2', '7', '8']
string

Summary

In this tutorial, I showed you ways to convert array of numbers to array of strings in JavaScript. These methods are easy to use, and I hope you will successfully apply the above methods.

You can read more other articles here, thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *