Convert Array of Strings to Array of Numbers in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 the result.

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

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.

We convert the string to a number on each iteration and then push the result to the numbers array.

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.