I have a variable `var num = 12;`

And I want to add both integers (`1 and 2`

) in the num to equal 3 in JavaScript. I’m doing this to an array of elements that has two digit numbers.

Can someone solve this? I have tried and I need help.

## Advertisement

## Answer

You could turn the number into an array of strings then use the map and reduce function to change them to numbers and add them together like so:

let num = 12; let sum = [...`${num}`].map(Number).reduce((a, b) => a + b); or [...`${num}`].reduce((a, b) => +a + +b);