1

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?

3
  • var myArray = [123,457,789] Commented 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. Commented 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? Commented Jan 28, 2016 at 4:35

2 Answers 2

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;

Sign up to request clarification or add additional context in comments.

1 Comment

Arrow functions save some space over arr.map(function(n){return (''+n).split('').reduce(function(sum, n){return sum + +n;},0);}) but support isn't ubiquitous.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.