Reputation: 41
I'm trying to add up all the numbers in each array and print out the total sum of that array. I'm not sure how to get this code done.
Example:
var myArray = [123, 456, 789]
I want the program to print out 6,15,24.
Since 1+2+3 = 6, 4+5+6=15 and 7+8+9= 24.
How would I go about adding each individual number in that array?
Upvotes: 1
Views: 418
Reputation: 87203
You can use Array#map
and Array#reduce
.
With ES2015 Arrow Function syntax
myArray.map(el => el.toString().split('').reduce((sum, b) => sum + +b, 0));
var myArray = [123, 456, 789];
var resultArr = myArray.map(el => el.toString().split('').reduce((sum, b) => sum + +b, 0));
console.log(resultArr);
document.body.innerHTML = resultArr; // FOR DEMO ONLY
In ES5:
myArray.map(function (el) {
return el.toString().split('').reduce(function (sum, b) {
return sum + +b
}, 0);
});
var myArray = [123, 456, 789];
var resultArr = myArray.map(function (el) {
return el.toString().split('').reduce(function (sum, b) {
return sum + +b
}, 0);
});
console.log(resultArr);
document.body.innerHTML = resultArr;
Upvotes: 2
Reputation: 1468
You have to decompose each to number to its digits, you can use modulo operator for that.
For example, X mod 10 will always get the rightmost digit from X, and to remove the last digit of X you have to make an integer division, X div 10.
function parse(array) {
return array.map(function(item) {
var n = 0;
while (item > 0) {
n += item % 10;
item = Math.floor(item/10);
}
return n;
});
}
Upvotes: 0