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?
-
var myArray = [123,457,789]Tyler– Tyler2016年01月25日 04:48:37 +00:00Commented Jan 25, 2016 at 4:48
-
You might consider map to create a new array from values in the current array, and reduce to create a single value from the digits in each number.RobG– RobG2016年01月25日 04:49:37 +00:00Commented Jan 25, 2016 at 4:49
-
I hope your problem is solved, If it is consider accepting the best answer. See How does accepting an answer work?Tushar– Tushar2016年01月28日 04:35:28 +00:00Commented Jan 28, 2016 at 4:35
2 Answers 2
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;
1 Comment
arr.map(function(n){return (''+n).split('').reduce(function(sum, n){return sum + +n;},0);}) but support isn't ubiquitous.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;
});
}