# How to Sum All The Digits in a Number

## Put in practice the String and Number built-in functions, the split and reduce methods

This post shows a different solution to the problem of computing the sum of the digits in a number.

The first step is to convert the number to an array of digits. To achieve this we first convert it to a string, then convert the string into an array of chars. In the end, the array of number characters is converted into an array of numbers.

The `String`

built-in function can transform any value into a string. Below is an example of transforming a number into a string.

`String(12345)`

//"12345"

The `split`

method splits a text into an array of substrings based on a separator. It does not change the original string. Here is an example of using the empty string (`''`

) as a separator.

`"12345".split('')`

//["1","2","3","4","5"]

The `Number`

built-in in function can transform any value into a number. Here is an example of converting a string into a number.

`Number("1")`

//1

The `map`

array method transforms an array of values into a new array of transformed values using a mapping function. Below is an example of using the `Number`

built-in function as a mapping function.

`["1","2","3","4","5"].map(Number)`

//[1,2,3,4,5]

Here is how we can put together all these functions and convert the number to an array of digits.

`const number = 12345;`

const digits = String(number)

.split('')

.map(Number);

console.log(digits);

//[1, 2, 3, 4, 5]

Once we have transformed the number into an array of digits we can use the `reduce`

array method to compute the sum.

function sum(x, y) {

return x + y;

}const number = 12345;

const total = String(number)

.split('')

.map(Number)

.reduce(sum, 0)

console.log(total);

//15

The `reduce(reducer, value)`

method converts an array into an aggregate value using a reducer function. The second parameter of the function defines the initial value of the aggregate value.

The reducer function takes the aggregate value and the current value and returns the new aggregate value.

In our example `sum`

is the reducer function.

`step 1, x = 0, y = 1 -> new aggregate = 1`

step 2, x = 1, y = 2 -> new aggregate = 3

step 3, x = 3, y = 3 -> new aggregate = 6

step 4, x = 6, y = 4 -> new aggregate = 10

step 5, x = 10,y = 5 -> new aggregate = 15

Thanks for reading.