vendredi 10 mai 2019

Return sum of even numbers in an array

The solution I am looking for: My function needs to return the sum of all the even numbers in my array. The expected answer is 30.

The problem I am having: The answer it is returning is 25.

let numStr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const sumEvens = (numStr) => {
  let sum = 0;
  for (let i = 0; i < numStr.length; i++) {
    if (i % 2 === 0){ 
    sum = sum + numStr[i];
    }
  }
  return sum;
}
 
console.log(sumEvens(numStr));

I changed the function to push to a sum array and returned the sum array to find the reason it is returning 25 is because it is making an array of odd numbers instead of the even.

let numStr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const sumEvens = (numStr) => {
  let sum = [ ];
  for (let i = 0; i < numStr.length; i++) {
    if (i % 2 === 0){ 
    sum.push(numStr[i]);
    }
  }
  return sum;
}
 
console.log(sumEvens(numStr));

The only way I am able to get the correct output of 30 is to make my if statement if (i % 2 !== 0), but I know that means to only add if the number in the array is NOT even.

I feel like I am so close, but missing one minor thing. The other SO posts and MDN did not help me.

Aucun commentaire:

Enregistrer un commentaire