This post will discuss how to convert a string array to a number array in JavaScript.

There are several ways to convert a string array to a number array in JavaScript. Here are some of the most common functions:

1. Using Array.map() function

The Array.map() function creates a new array by applying a function to each element of the original array. We can use it with the Number() function, which is the standard function to convert a string to a number. The map() function applies the Number() function to each element of the string array and returns a new array of numbers with the results. Here’s an example:

Download  Run Code

 
Another option is to use the parseInt() function with the map() function. The parseInt() function parses a string and returns an integer. The map() function applies the parseInt() function to each element of the string array and returns a new array of integers. The parseInt() function takes a second argument that specifies the radix (base) of the input string. Here’s an example:

Download  Run Code

 
We can also use this function to create a new array with the results of applying the unary plus operator (+) to every element in the original array. The unary plus operator converts a string to a number. Here’s an example:

Download  Run Code

 
Note if the string is not a valid number, all the above mapping functions returns NaN (Not a Number). For example, a string array like ["1", "two", "3"] will result in the array [1, NaN, 3].

2. Using push() function

The push() function adds one or more elements to the end of an array. We can use a for loop or a for…of loop to iterate over the string array and convert each element to a number using the appropriate mapping functions. Then we can use the push() function to add the converted element to a new array. Here’s an example using the Number() function:

Download  Run Code

 
We can also use forEach() function to iterate over the original array and push the parsed integer values to a new array. Here’s an example using the parseInt() function:

Download  Run Code

That’s all about converting a string array to a number array in JavaScript.