DEV Community

Avnish
Avnish

Posted on

Split a Number into an Array in JavaScript

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]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. String(number) converts the number 123456 to a string, resulting in the string '123456'.
  2. .split('') splits the string into an array of individual characters, resulting in ['1', '2', '3', '4', '5', '6'].
  3. .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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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)