Last updated: Mar 3, 2024
Reading timeยท2 min
To sum all the digits in a number:
split()
method to split the string into an array of digits.reduce()
method to sum up all the digits in the array.function getSumOfDigits(num) { return String(num) .split('') .reduce((accumulator, digit) => { return accumulator + Number(digit); }, 0); } console.log(getSumOfDigits(1)); // ๐๏ธ 1 console.log(getSumOfDigits(123)); // ๐๏ธ 6 console.log(getSumOfDigits(1234)); // ๐๏ธ 10
The function takes a number as a parameter and returns the sum of the digits of the number.
We used the String() constructor to convert the number to a string and then used the String.split() method to split the string into an array of digits.
console.log('1'.split('')); // ๐๏ธ ['1'] console.log('123'.split('')); // ๐๏ธ ['1', '2', '3'] console.log('1234'.split('')); // ๐๏ธ ['1', '2', '3', '4']
We passed an empty string to the String.split()
method to split the string on
each character (digit).
The last step is to use the Array.reduce() method to iterate over the array.
function getSumOfDigits(num) { return String(num) .split('') .reduce((accumulator, digit) => { return accumulator + Number(digit); }, 0); } console.log(getSumOfDigits(1)); // ๐๏ธ 1 console.log(getSumOfDigits(123)); // ๐๏ธ 6 console.log(getSumOfDigits(1234)); // ๐๏ธ 10
The function we passed to the reduce()
method gets called with each element
(digit) in the array.
The second argument we passed to the method is the initial value for the
accumulator
variable.
On each iteration, we return the sum of the accumulator
and the current digit.
Whatever we return from the callback function gets passed as the accumulator
on the next iteration.
Once the reduce()
method iterates over the entire array, we have the sum of
all the digits in the number.
Alternatively, you can use a while
loop.
while
loopThis is a three-step process:
sum
variable to 0
.sum
variable.function getSumOfDigits(num) { let initialNumber = num; let sum = 0; while (initialNumber) { sum += initialNumber % 10; initialNumber = Math.floor(initialNumber / 10); } return sum; } console.log(getSumOfDigits(1)); // ๐๏ธ 1 console.log(getSumOfDigits(123)); // ๐๏ธ 6 console.log(getSumOfDigits(1234)); // ๐๏ธ 10
We used a while
loop to iterate for as long as the initialNumber
variable
stores a truthy value (not 0
).
On each iteration, we use the modulo %
operator to get the remainder of
dividing the number by 10
.
console.log(1234 % 10); // ๐๏ธ 4 console.log(123 % 10); // ๐๏ธ 3 console.log(12 % 10); // ๐๏ธ 2
The expression returns the last digit of the number.
The next step is to reassign the initialNumber
variable so that the last digit
is removed.
On each iteration, we get the last digit of the number and add it to the sum
variable.
You can learn more about the related topics by checking out the following tutorials: