ScottC
ScottC

Reputation: 49

Sum of a number's digits with JavaScript

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?

Upvotes: 4

Views: 7257

Answers (5)

nikhil kumar
nikhil kumar

Reputation: 11

var nums = [333, 444, 555]; 

nums.map(number => [...String(number)].reduce((acc, num) => +num+acc , 0));


//output [9, 12, 15]

Unary plus operator (+num) is converting string into integer.

Upvotes: 1

robe007
robe007

Reputation: 3937

Now in our days, with the advantages of ES6, you can simply spread each value of your array inside map, and the with reduce make the operation:

var numbers = [333, 444, 555];

const addDigits = nums => nums.map(
      num => [...num.toString()].reduce((acc, act) => acc + parseInt(act), 0)
);

console.log(addDigits(numbers));

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 241048

If you want to generate an array consisting of the sum of each digit, you can combine the .map()/.reduce() methods. The .map() method will create a new array based on the returned value (which is generated on each iteration of the initial array).

On each iteration, convert the number to a string (num.toString()), and then use the .split() method to generate an array of numbers. In other words, 333 would return [3, 3, 3]. Then use the .reduce() method to add the current/previous numbers in order to calculate the sum of the values.

var input = [333, 444, 555];

var sumOfDigits = input.map(function(num) {
  return num.toString().split('').reduce(function(prev, current) {
    return parseInt(prev, 10) + parseInt(current, 10);
  }, 0);
});

//Display results:
document.querySelector('pre').textContent =
  'Input: ' + JSON.stringify(input, null, 4)
   + '\n\nOutput: ' + JSON.stringify(sumOfDigits, null, 4);
<pre></pre>

Upvotes: 0

Sebastian Simon
Sebastian Simon

Reputation: 19495

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().

Upvotes: 2

m.antkowicz
m.antkowicz

Reputation: 13581

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

Upvotes: 8

Related Questions