Sum all the Digits in a Number using JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

banner

Photo by Levi Morsy

Sum all the Digits in a Number using JavaScript #

To sum all of the digits in a number:

  1. Convert the number to a string and use the split() method to split it into an array of strings.
  2. Call the reduce() method on the array and sum the accumulator with each array element converted back to a number.
index.js
function getSumOfDigits(num) { return String(num) .split('') .reduce((acc, curr) => { return acc + Number(curr); }, 0); } console.log(getSumOfDigits(1)); // ๐Ÿ‘‰๏ธ 1 console.log(getSumOfDigits(123)); // ๐Ÿ‘‰๏ธ 6 console.log(getSumOfDigits(1234)); // ๐Ÿ‘‰๏ธ 10

We created a reusable functions to get the sum of all digits in a number.

The first thing we do is convert the number to a string, using the String object.

We then call the String.split method on the string to get an array containing the digits as elements.

index.js
console.log('1'.split('')); // ๐Ÿ‘‰๏ธ ['1'] console.log('123'.split('')); // ๐Ÿ‘‰๏ธ ['1', '2', '3'] console.log('1234'.split('')); // ๐Ÿ‘‰๏ธ ['1', '2', '3', '4']
The parameter we passed to the split method is a separator (on which character we want to split the string). Because we want each digit to be its own array element we supplied an empty string.

The last step is to use the Array.reduce method on the array of strings.

The function we passed to the reduce method gets called with each element (string) in the array.

The second parameter we passed to the method is the initial value for the acc (accumulator) variable.

On each iteration we return the sum of the current accumulator and the current array element casted back to a number to get the value for the acc variable for the next iteration.

Once the reduce method iterates over the entire array, we have the sum of all the digits in the number.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee