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'
}
CodePudding user response:
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'
CodePudding user response:
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));
CodePudding user response:
digsum
is a number but you're trying to access it as an array (digsum[j]
). You probably want to overwrite the array with digsum
's value for each index, e.g. after the while
block: arrChars[i] = digsum;