In this article, we have given an array of strings and the task is to convert it into an array of numbers in JavaScript.
Input: ["1","2","3","4","5"] Output: [1,2,3,4,5] Input: ["10","21","3","14","53"] Output: [10,21,3,14,53]
There are two methods to do this, which are given below:
Method 1: Array traversal and typecasting.
In this method, we traverse an array of strings and add it to a new array of numbers by typecasting it to an integer using the parseInt() function.
Javascript
// Create an array of string var stringArray = [ "1" , "2" , "3" , "4" , "5" ]; // Create an empty array of number var numberArray = []; // Store length of array of string // in variable length length = stringArray.length; // Iterate through array of string using // for loop // push all elements of array of string // in array of numbers by typecasting // them to integers using parseInt function for ( var i = 0; i < length; i++) // Instead of parseInt(), Number() // can also be used numberArray.push(parseInt(stringArray[i])); // Print the array of numbers console.log(numberArray); |
Output:
[1, 2, 3, 4, 5]
Method 2: Using map() method of JavaScript.
In this method, we use the array map method of JavaScript.
Javascript
// Create an array of string var stringArray = [ "10" , "21" , "3" , "14" , "53" ]; // Create a numberArray and using // map function iterate over it // and push it by typecasting into // int using Number var numberArray = stringArray.map(Number); // Print the array of numbers console.log(numberArray); |
Output:
[10, 21, 3, 14, 53]
Method 3: Using forEach loop of JavaScript.
In this method, we use the array forEach loop of JavaScript.
Javascript
// Create an array of string var stringArray = [ "10" , "21" , "3" , "14" , "53" ]; // Create a numberArray and using // forEach loop iterate over it // and push it to numberArray with typecasting it into // int using + operator var numberArray = []; stringArray.forEach( ele => numberArray.push(+ele)) // Print the array of numbers console.log(numberArray); |
Output:
[ 10, 21, 3, 14, 53 ]
Method 4: Using reduce method of JavaScript.
In this method, we use the reduce function of JavaScript.
Javascript
// Create an array of string var stringArray = [ "10" , "21" , "3" , "14" , "53" ]; // Create a numberArray and using // reduce function iterate over it // and push it to numberArray with typecasting it into // int using + operator var numberArray = stringArray.reduce( (acc, x ) => acc.concat(+x), []) // Print the array of numbers console.log(numberArray); |
Output:
[ 10, 21, 3, 14, 53 ]