Skip to content
Advertisement

How do it make “`var num = 12;“` to be equal to 3 using javascript? [closed]

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);

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement