'I am getting NaN when looping over an array inside an if statement. How can I sum up an array of even and odd nums?
I am trying to extra even and odd numbers of number(10), however when I try to sum the m5 which is an array of even numbers, I get the NaN. How can I add the sum of 5 and 3 in my loop?
let number = 10;
let array1 = new Array();
let m5 = new Array();
let m3 = new Array();
let sum5 = 0;
let sum3 = 0;
let arraySum = 0;
for (let i=0; i <= number; i++) {
array1.push(i)
if (array1[i] % 5 === 0 && array1[i] < number) {
m5.push(i); // 0, 5
sum5 += m5[i];
console.log(sum5); //Return NaN
}
if (array1[i] % 3 === 0) {
m3.push(i)
}
arraySum += array1[i];
}
Solution 1:[1]
Your problem is an out of bounds issue. You are trying to push the value of i to the m5 array, but the index where this value is put is different. You need to track the index and the values separately. I created a variable j to track the index for the m5 array. You will need to do the same for array m3.
let number = 10;
let array1 = new Array();
let m5 = new Array();
let m3 = new Array();
let sum5 = 0;
let sum3 = 0;
let arraySum = 0;
for (let i=0, j=0; i <= number; i++) {
array1.push(i)
if (array1[i] % 5 === 0 && array1[i] < number) {
m5.push(i); // 0, 5
sum5 += m5[j++];
console.log(sum5); //Return the sum correctly
}
if (array1[i] % 3 === 0) {
m3.push(i)
}
arraySum += array1[i];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hfontanez |
