Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Joshua Earle
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.
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.
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:
forEach()
method to iterate over the strings array.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.
Array.forEach
method is not supported in Internet Explorer. If you have to support the browser, use the Array.map
approach instead.