4

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?

5 Answers 5

8

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)
});
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

A slight variant [333, 444, 555].map(function(d) { return d.toString().split('').reduce(function(acc, c) { return acc + parseInt(c,10); }, 0) }) , to illustrate d.toString().split('') as an alternative way to get the list of letters in string.
@widged You’re right… I got used a bit too much to the ES6 spread operator where you could do [...'String'] to get ['S','t','r','i','n','g'] or Array.from that I assumed it was fine to just use Array.prototype.slice.call everywhere as a replacement.
1

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

Comments

1
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.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.