To split a number into individual digits in JavaScript, you can convert the number to a string, iterate over each character in the string, and convert each character back to a number. Here’s how you can do it:

// Example number
const number = 123;

// Convert the number to a string
const numberString = number.toString();

// Initialize an array to store the digits
const digits = [];

// Iterate over each character in the string
for (let i = 0; i < numberString.length; i++) {
 // Convert the character back to a number and push it to the digits array
 digits.push(Number(numberString.charAt(i)));
}

// Now, digits array contains individual digits of the number
console.log(digits); // Output: [1, 2, 3]

 
Once you have the individual digits in an array, you can perform operations on them as needed. For example, you mentioned adding them together:

// Summing the digits
const sum = digits.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 6 (1 + 2 + 3)

You can incorporate this logic into your loop to split each number into individual digits and perform operations on them as necessary.

Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

Related Q&A