Convert Array of Numbers to Array of Strings in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Convert Array of Numbers to Array of Strings #

To convert an array of numbers to an array of strings, call the map() method on the array, and on each iteration, convert the number to a string. The map method will return a new array containing only strings.

index.js
const arrOfNum = [1, 2, 3]; const arrOfStr = arrOfNum.map(num => { return String(num); }); // ๐Ÿ‘‡๏ธ ['1', '2', '3'] console.log(arrOfStr);

The function we passed to the Array.map method gets called with each element (number) in the array.

On each iteration we convert the number to a string and return it.

The map method returns a new array that contains the values that the function returned, in our case an array containing all the strings.

Note that the Array.map method does not change the contents of the original array, it returns a new array.

An alternative approach is to use the Array.forEach method.

To convert an array of strings to an array of numbers:

  1. Declare a variable, that will store the strings and set it to an empty array.
  2. Use the forEach() method to iterate over the numbers array.
  3. On each iteration convert the number to a string and push it to the strings array.
index.js
const arrOfNum = [1, 2, 3]; const arrOfStr = []; arrOfNum.forEach(num => { arrOfStr.push(String(num)); }); // ๐Ÿ‘‡๏ธ ['1', '2', '3'] console.log(arrOfStr);

We used the Array.forEach method to iterate over the array of numbers.

The function we passed to the method, gets called with each element in the array.

On each iteration we convert the number to a string and push it to the strings array.

Note that the Array.forEach method is not supported in Internet Explorer. If you have to support the browser, use the Array.map approach instead.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee