How to use reduce() function In Javascript
- The reduce function is used to reduce the array into a single value and execute a provided function for each value of the array.
- Store the integer value in a variable.
- Typecast the integer into a string.
- Using the spread operator to form an array of characters.
- Iterate over that array using the reduce() method.
- Using the reduce() method convert the array of strings into an array of Integers.
Syntax:
array.reduce( function(total, currValue, currIndex, arr), initialValue )
Example: This example converts a number into an array using Array.reduce() method in Javascript.
let myInt = 235345;
// number to string conversion
let temp = '' + myInt
// forming array with numbers as element
let intArr = [...temp].reduce((acc, n) => acc.concat(+n), []);
// Print the result array
console.log(intArr);
Output:
[ 2, 3, 5, 3, 4, 5 ]
How to convert a number into array in JavaScript ?
In this article, we have been given a number and the task is to convert the given number into an array using JavaScript.
These are the following methods by using these we can solve this problem:
Table of Content
- Using Array.from() Method
- Using map() Method
- Using reduce() function
- Using Lodash _.toArray() Method
- Using mathematical operations
- Using a for loop to iterate through the string representation
Contact Us