Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of a number's digits with JavaScript

Tags:

javascript

sum

I have:

var nums = [333, 444, 555]; 

I want to treat each digit in a number as a separate number and add them together. In this case sums should be:

9 = 3 + 3 + 3
12 = 4 + 4 + 4
15 = 5 + 5 + 5 

How to achieve this using JavaScript?

like image 410
ScottC Avatar asked Sep 18 '25 19:09

ScottC


2 Answers

you can use a simple modulo operation and dividing

var a = [111, 222, 333];

a.forEach(function(entry) {
    var sum = 0;
    while(entry > 0) 
    {
        sum += entry%10;
        entry = Math.floor(entry/10);
    }
    alert(sum)
});
like image 173
m.antkowicz Avatar answered Sep 20 '25 10:09

m.antkowicz


Here’s a different approach that converts the numbers to strings and converts those into an array of characters, then the characters back into numbers, then uses reduce to add the digits together.

var nums = [333, 444, 555];
var digitSums = nums.map(function(a) {
  return Array.prototype.slice.call(a.toString()).map(Number).reduce(function(b, c) {
    return b + c;
  });
});
digitSums; // [9, 12, 15]

If your array consists of bigger numbers (that would overflow or turn to Infinity), you can use strings in your array and optionally remove the .toString().

like image 31
Sebastian Simon Avatar answered Sep 20 '25 09:09

Sebastian Simon