0

I am new to Javascript and at the moment I'm learning how "arrays" are used.

In my code below I have 12 numbers held by an array variable. Next, the for loop is iterating over the indexes to check which values have 2 or more digits, the while-loop then summarizes the digits (e.g. value '130' at index 8, will be 1+3+0=4).

Final step..and also where I'm stuck:

I need to sum up all the "new" index values and return the result in a variable. With the numbers provided in the code, the result would be '50'.

Anyone have clue on how to do this? I've tried the conventional for-loop with sum += array[i], but it doesn't work.

var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];

for (var i = 0; i < arrChars.length; i++) {
  var digsum = 0;

  while (arrChars[i] > 0) {
    digsum += arrChars[i] % 10;

    arrChars[i] = Math.floor(arrChars[i] / 10);
  }

  var sum = 0; // this last part won't work and I just get "nan", 12 times

  for (var j = 0; j < arrChars.length; j++) {
    sum += parseInt(digsum[j]);
  }

  console.log(sum); // desired output should be '50'
}

2
  • 1
    digsum is not an array Commented Jul 14, 2022 at 12:47
  • I figured that but the result from the while-loop is stored in the digsum-variable. How can the values from digsum be summarized? Commented Jul 14, 2022 at 12:54

2 Answers 2

1

Move digsum outside and it will contain the sum of every number in it:

var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];

var digsum = 0;
for (var i = 0; i < arrChars.length; i++) {

  while (arrChars[i] > 0) {
    digsum += arrChars[i] % 10;

    arrChars[i] = Math.floor(arrChars[i] / 10);
  }
}
console.log(digsum); // desired output should be '50'

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

1 Comment

Thanks! I kinda guessed this one would be solved quick but I just didn't see this obvious solution!
1

I'd make this easy and just flatten the array of numbers into a string of digits, split that into an array of single digits, and add them together:

var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];

console.log([...arrChars.join('')].reduce((agg, cur) => agg += +cur, 0));

1 Comment

Thanks! This solution is really nice and I will definitely look into these functions as next step in my learning process.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.