In this article we will learn how to split numbers into a map in JavaScript.
It is very common to split numbers into a map in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to split a numbers into a map.
Imagine we have some numbers like this:
123456
And we want to split these numbers into a map.
Expected output will be like that:
[1, 2, 3, 4, 5, 6]
How to solve this problem?
The solution to this problem is easy, but we will use some steps to solve this problem:
- Use the
String()
constructor to convert the number to a string. - Use
Array.from
to split numbers into an array. - Use
Map
to convert each string into a number again.
Solution:
As we said before, we will use some steps to solve this problem.
First we need to convert our numbers into a string.
// Numbers
const numbers = 123456;
// Convert to string
const toString = String(numbers);
// Result:
console.log(toString);
Output
123456
Now we want to convert our string into an array using Array.from()
.
// Numbers
const numbers = 123456;
// Convert to string
const toString = String(numbers);
// Convert to an array
const toArray = Array.from(toString);
// Result:
console.log(toArray);
Output
[ '1', '2', '3', '4', '5', '6' ]
Now, as you can see, half of the problem has been successfully solved, because there is still another problem, which is that the array contains numbers, but it is of string type, now we have to convert the string to numbers using Map
.
// Numbers
const numbers = 123456;
// Convert to a string
const toString = String(numbers);
// Convert to an array
const toArray = Array.from(toString);
// Convert to numbers
const result = toArray.map(ele => {
return Number(ele);
});
// Result:
console.log(result);
Output
[ 1, 2, 3, 4, 5, 6 ]
Thank you for reading
Thank you for reading my blog. 🚀