How could you get the sum of figures from a number of 2 or more numerals .
For example:
The sum of figures of 134 in javascript.
How could you get the sum of figures from a number of 2 or more numerals .
For example:
The sum of figures of 134 in javascript.
An alternative:
To generate an array of characters from a string you can use the split
method by passing it an empty string as an argument.
To calculate the sum of the characters of the array you can use the reduce
method to add each of the characters converted to a number.
In this way the addition function could stay:
function suma(cadena){
if (!cadena) return 0;
return cadena.split('').reduce((r, c) => r += parseInt(c), 0);
}
A working example:
document.getElementById('calcular').addEventListener(
'click',
function(){
var numero = document.getElementById('numero').value;
document.getElementById('resultado').innerText = suma(numero);
}
);
function suma(cadena){
if (!cadena) return 0;
return cadena.split('').reduce((r, c) => r += parseInt(c), 0);
}
<input type="number" id="numero"><button id="calcular">Calcular</button>
<br /> <br/>
Resultado: <span id="resultado"></span>
You can do it in a simple line.
(123).toString().split('').reduce((total, actual) => total + +actual, 0)
How to add the figures of a number, steps that are followed in this answer:
var numero = 111111,
salida = [],
cadenaNumero = numero.toString();
for (var i = 0, len = cadenaNumero.length; i < len; i += 1) {
salida.push(+cadenaNumero.charAt(i));
}
console.log(salida);
for (var i = 0, sum = 0; i < salida.length; sum += salida[i++]);
console.log(sum);
Another possibility is to do the sum directly without building the array of digits:
var numero = 111111,
salida = [],
cadenaNumero = numero.toString();
suma=0;
for (var i = 0, len = cadenaNumero.length; i < len; i += 1) {
suma+=(+cadenaNumero.charAt(i));
}
console.log(suma);