Convert Array of Numbers to Array of Strings in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 20, 2021

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.