How to use a for loop In Javascript
To convert an array of strings to numbers using a `for` loop, iterate through each string, convert it to a number using `Number()`, and push it to a new array. This method provides control and flexibility for handling each element individually.
Example: here we are following above mentioned apporach.
const stringArray = ["1", "2", "3", "4", "5"];
const numberArray = [];
for (let i = 0; i < stringArray.length; i++) {
numberArray.push(Number(stringArray[i]));
}
console.log(numberArray); // Output: [1, 2, 3, 4, 5]
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