How to use reduce method In 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.
// Create an array of string
let 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
let numberArray = stringArray.reduce( (acc, x ) => acc.concat(+x), [])
// 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
Contact Us