Open In App

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:

Method 1: Using Array.from() Method

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 ]

Method 2: Using map() Method

Syntax:

array.map(function(currentValue, index, arr), thisValue)

Example: This example converts a number into an array using Array.map() method in Javascript.




// Declare a variable and store an
// integer value
let num = 235345
 
// Here we typecasting the num
// Splitting the num, so that
// we got an array of strings
// Then use map function to
// convert the array of strings
// into array of numbers
 
let myArr = String(num).split("").map((num) => {
    return Number(num)
})
 
console.log(myArr)

Output:

[2, 3, 5, 3, 4, 5]

Method 3: Using reduce() function

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 ]

Method 4: Using Lodash _.toArray() Method

Example: This example shows the implementation of the above-explained approach.




// Requiring the lodash library
const _ = require("lodash");
     
// Use of _.toArray() method
console.log(_.toArray(2345));
console.log(_.toArray(6789));

Output:

2345
6789

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


Article Tags :