Sum of numbers of a number in Javascript

-1

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.

    
asked by user889 10.04.2018 в 08:20
source

3 answers

1

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>
    
answered by 10.04.2018 в 08:37
1

You can do it in a simple line.

(123).toString().split('').reduce((total, actual) => total + +actual, 0)
    
answered by 10.04.2018 в 08:40
0

How to add the figures of a number, steps that are followed in this answer:

  • Convert number to string.
  • Iterate over that string and save in an array each character converted to a number
  • Iterate over the array of numbers and add each element
  • 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);

    Source

    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);
        
    answered by 10.04.2018 в 08:31