How to use Array.from() Method In Javascript
- The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object.
- In this approach, Store a number in a variable.
- Use Array.from() method and in its first parameter enter the string type cast value.
- In the second parameter, we use a function i.e. myFunc, at every iteration the function will be called.
- The myFunc function will take a parameter that was returned by the iteration of Array.from() method. We typecast the number into a string so the type of parameter is a string, but we will typecast it into an integer and return it.
- The value returned by the Array.from() is our result.
Syntax :
Array.from(object, mapFunction, thisValue)
Example: This example converts a number into an array using Array.from() method in Javascript.
let myInt = 235345;
// Getting the string as a parameter
// and typecasting it into an integer
let myFunc = num => Number(num);
let intArr = Array.from(String(myInt), myFunc);
// 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