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.

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

Similar Reads

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....

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....

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....

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....

Using a for loop

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....