Convert array of numbers to array of strings using JavaScript
This post will discuss how to convert an array of numbers to an array of strings using JavaScript.
There are several methods to convert an array of numbers to an array of strings using JavaScript. Here are some of the methods that we can use:
1. Using Array.map() function
A simple and common way to convert an array of numbers to an array of strings is to use the Array.map() function and passing the String() constructor as a function, which will turn each number into a string. This will create a new array with the results of calling the String constructor on every element in the original array. Here’s an example:
|
1 2 3 4 5 |
let numArray = [1, 2, 3, 4, 5]; let strArray = numArray.map(String); console.log(strArray); // ['1', '2', '3', '4', '5'] |
2. Using Array.join() and String.split() function
Another way to convert an array of numbers to an array of strings is to use the join() function with the split() function. We can use these functions to join the elements of the original array into a string, separated by a delimiter, and then split the string into an array of strings using the same delimiter. However, it requires two iterations and an intermediate string to be created. Here’s an example:
|
1 2 3 4 5 |
let numArray = [1, 2, 3, 4, 5]; let strArray = numArray.join(",").split(","); console.log(strArray); // ['1', '2', '3', '4', '5'] |
3. Using Array.from() function
A third way to convert an array of numbers to an array of strings is to use Array.from() function. This function creates a new array from an iterable object, such as an array, and optionally applies a callback function to each element. We can use the toString() function to convert each number to a string. For example, we can use these functions together to create a new string array using the elements of number array, as follows:
|
1 2 3 4 5 |
let numArray = [1, 2, 3, 4, 5]; let strArray = Array.from(numArray, x => x.toString()); console.log(strArray); // ['1', '2', '3', '4', '5'] |
That’s all about converting an array of numbers to an array of strings using JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)