Title : Split a Number into an Array in JavaScript
let's split a number into an array in JavaScript using the specified steps:
Example 1:
const number = 123456;
const array = String(number).split('').map(Number);
console.log(array); // Output: [1, 2, 3, 4, 5, 6]
Explanation:
-
String(number)
converts the number123456
to a string, resulting in the string'123456'
. -
.split('')
splits the string into an array of individual characters, resulting in['1', '2', '3', '4', '5', '6']
. -
.map(Number)
maps each element of the array to its numeric equivalent, resulting in[1, 2, 3, 4, 5, 6]
.
Example 2:
const number = 987654;
const array = String(number).split('').map(Number);
console.log(array); // Output: [9, 8, 7, 6, 5, 4]
Explanation:
- Same steps as above, but applied to the number
987654
, resulting in[9, 8, 7, 6, 5, 4]
.
Example 3:
const number = 1000;
const array = String(number).split('').map(Number);
console.log(array); // Output: [1, 0, 0, 0]
Explanation:
- Same steps as above, but applied to the number
1000
, resulting in[1, 0, 0, 0]
.
Example 4:
const number = 123;
const array = String(number).split('').map(Number);
console.log(array); // Output: [1, 2, 3]
Explanation:
- Same steps as above, but applied to the number
123
, resulting in[1, 2, 3]
.
Example 5:
const number = 987;
const array = String(number).split('').map(Number);
console.log(array); // Output: [9, 8, 7]
Explanation:
- Same steps as above, but applied to the number
987
, resulting in[9, 8, 7]
.
In each example, we convert the number into a string, split it into individual characters, and then convert each character back into a number. This results in an array where each element represents a digit of the original number.
Top comments (0)