Convert Array of Strings to Array of Numbers in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Joshua Earle

Convert Array of Strings to Array of Numbers #

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

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

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

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

The map method returns a new array that contains the values that the function returned, in our case all of the numbers.

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 numbers and set it to an empty array.
  2. Use the forEach() method to iterate over the strings array.
  3. On each iteration convert the string to a number and push it to the numbers array.
index.js
const arrOfStr = ['1', '2', '3']; const arrOfNum = []; arrOfStr.forEach(str => { arrOfNum.push(Number(str)); }); // ๐Ÿ‘‡๏ธ [1, 2, 3] console.log(arrOfNum);

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

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

On each iteration we convert the string to a number and push it to the numbers 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