2

I want to Split a number into its digit (for example 4563 to 4 , 5 , 6 , 3 ) then addiction this digits. (for example: 4+5+6+3=18)

I can write code for 3 digit or 2 digit and ... numbers seperately but I cant write a global code for each number.

so this is my code for 2 digit numbers:

var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5

and this is my code for 3 digit numbers:

var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15

but I cant write a code to work with each number.How can I write a global code for each number?

Roberto
  • 23
  • 1
  • 1
  • 5

9 Answers9

5

In modern browsers you can do an array operation like

var num = 4563;
var sum = ('' + num).split('').reduce(function (sum, val) {
    return sum + +val
}, 0)

Demo: Fiddle

where you first create an array digits then use reduce to sum up the values in the array

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
3

var num = 4563;
var sum = 0;
while(num > 0) {
  sum += num % 10;
  num = Math.floor(num / 10);
}
console.log(sum);
Feyyaz
  • 3,147
  • 4
  • 35
  • 50
0

This solution converts the number to string, splits it into characters and process them in the callback function (prev is the result from the previous call, current is the current element):

var a = 456;
var sum = a.toString().split("").reduce(function(prev, current){
    return parseInt(prev) + parseInt(current)
})
Matt
  • 25,467
  • 18
  • 120
  • 187
steo
  • 4,586
  • 2
  • 33
  • 64
0

Do number%10(modulus) and then number/10(divide) till the number is not 0

Bhavik Shah
  • 358
  • 4
  • 11
0

I hope the following example is useful to you:

var text="12345";
var total=0;
for (i=0;i<text.length;i++)
{
  total+= parseInt(text[i]);
}    
alert(total);
The KNVB
  • 3,588
  • 3
  • 29
  • 54
0

Here is how I would approach the problem. The trick I used was to split on the empty string to convert the string to an array and then use reduce on the array.

function digitSum(n) {
    // changes the number to a string and splits it into an array
    return n.toString().split('').reduce(function(result, b){
        return result + parseInt(b);
    }, 0);
}

As mentioned by several other posters (hat tip to my commenter), there are several other good answers to this question as well.

2ps
  • 15,099
  • 2
  • 27
  • 47
  • 1
    There is already [another answer](http://stackoverflow.com/a/30025928) on this question from 2015 that suggests this approach. [Two in fact](http://stackoverflow.com/a/30025921). – Bryan Dec 27 '16 at 23:26
0

Here is my solution using ES6 arrow functions as call back. - Convert the number into a string. - Split the string into an array. - Call the map method on that array. - Callback function parse each digit to an array.

let number = 65535;

//USING MAP TO RETURN AN ARRAY TO DIGITS
let digits = number.toString()
                    .split("")
                    .map(num => parseInt(num));
//OUTPUT TO DOM
digits.forEach(
  digit => 
  document.querySelector("#out").innerHTML += digit + "<br>"
);
<p id="out"></p>
0

1) You can cast input number to string, using .toString() method and expand it into array with spread (...) operator

const splitNumber = n => [ ...n.toString() ]

2) Another short way - using recursion-based solution like:

const splitNumber = n => n ? [ ...splitNumber(n/10|0), n%10 ] : []
Mixalloff
  • 827
  • 4
  • 10
0
<div style="text-align:center; margin:auto;">
This script limits the number of characters in the INPUT field to those specified in the QUANT field.
<form>
<input name="" type="number" id="quant" value = "" style="padding:6px; margin:0.8em;" /><br />
<input name="" type="number" id="input" oninput="calc()" style="padding:6px;  margin:0.8em;" /><br />
<input type="reset" style="width:150px;padding:8px; margin:0.8em;">
</form>
<div id="digit"></div><br />
<script>
let input;
let out = '';
let total = '';
let quant = "";

function calc(){
  quant = document.getElementById('quant').value;
  input = document.getElementById('input').value;
  total = input.split('');
  if(total.length > quant){
      document.getElementById('input').value = "";
      for(i=0; i < quant; i++){
          document.getElementById('input').value += total[i];
      }
}
out = total.length - 1;
if(out < 0){
   out = 0;
}
document.getElementById('digit').innerText = "Quantity: " + out;
}
</script>
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 11 '23 at 19:02