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?
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)
});
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With