How to convert array of strings to array of numbers in JavaScript ?
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.
Example: In this example, we are using Array traversal and typecasting.
Javascript
let stringArray = [ "1" , "2" , "3" , "4" , "5" ];
let numberArray = [];
length = stringArray.length;
for (let i = 0; i < length; i++)
numberArray.push(parseInt(stringArray[i]));
console.log(numberArray);
|
Method 2: Using map() method of JavaScript
Javascript map() method creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, the map() method is used to iterate over an array and call function on every element of the array.
Example: In this example, we use the array map method of JavaScript.
Javascript
let stringArray = [ "10" , "21" , "3" , "14" , "53" ];
let numberArray = stringArray.map(Number);
console.log(numberArray);
|
Output
[ 10, 21, 3, 14, 53 ]
Method 3: Using forEach loop of JavaScript
The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array.
Example: In this example, we are using the array forEach loop of JavaScript.
Javascript
let stringArray = [ "10" , "21" , "3" , "14" , "53" ];
let numberArray = [];
stringArray.forEach( ele => numberArray.push(+ele))
console.log(numberArray);
|
Output
[ 10, 21, 3, 14, 53 ]
Method 4: Using reduce method of JavaScript
The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.
Example: In this example, we are using the reduce function of JavaScript.
Javascript
let stringArray = [ "10" , "21" , "3" , "14" , "53" ];
let numberArray = stringArray.reduce( (acc, x ) => acc.concat(+x), [])
console.log(numberArray);
|
Output
[ 10, 21, 3, 14, 53 ]
Last Updated :
22 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...