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

Tags:



I have a variable var num = 12; And i want to add both integers (1 and 2) in the num to equals 3 in javascript.

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

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



Source: stackoverflow