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.
// Create an array of string
let stringArray = ["1", "2", "3", "4", "5"];
// Create an empty array of number
let numberArray = [];
// Store length of array of string
// in letiable 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 (let 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 ]
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:
Table of Content
- Array traversal and typecasting
- Using map() method of JavaScript
- Using forEach loop of JavaScript
- Using reduce method of JavaScript
- Using a for loop