How to use forEach loop In 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.
// Create an array of string
let 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
let numberArray = [];
stringArray.forEach( ele => numberArray.push(+ele))
// Print the array of numbers
console.log(numberArray);
Output
[ 10, 21, 3, 14, 53 ]
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