Complete the function sumOddNumbers such that it returns the sum of all the odd numbers from the numbers parameter it receives.
The function should also work for negative numbers."
I tried:
function sumOddNumbers(numbers) {
let sum = 0;
numbers.forEach(function(number) { // array item (singular)
if (number % 2 === 1) {
sum = sum + number;
}
else if (number < 0) {
if (number % 2 === 1) {
sum = sum + number;
}
}
else {
console.log(“Positive/even number spotted.”);
}
});
return sum;
}
I don’t understand why the negative odd numbers don’t add to the sum?
Edit: I fixed the problem. The problem is solved now.
else if (number < 0) {
if (number % 2 === 1) {
sum = sum + number;
}
In above section number%2 will return -1 rather than 1, so -ve odd numbers can’t pass this statement and that’s the reason, and bcoz it number is -ve it will subtract from ‘sum’ rather than adding, you can use Math.abs()
BTW here is a short method to solve this problem
Mod edit : solution redacted
Here “e%2!=0” will filter all odd numbers and Math.abs will turn all numbers into +ve integers.