Reputation: 27
I'm trying to count the number of odd and even numbers in an array by using the Array.reduce() method. When I run the below code, I get the error "odd is not defined." How/where do I define odd to get this code to work?
var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
if (number % 2 === 1) {
counts[odd]++
} else {
counts[even]++;
}
return counts;
}, {});
Upvotes: 1
Views: 8301
Reputation: 1
Answer using ES6+
const sumEvenOdd = (numbersArray) => {
return numbersArray.reduce((acc, current) => current % 2 === 0 ? {...acc,'even':acc['even'] + current} : {...acc, 'odd':acc['odd'] + current}, {"even":0, "odd":0})
}'
console.log(sumEvenOdd([1, 6, 8, 5, 3]));
// Expected results: {even: 14, odd: 9}
Upvotes: 0
Reputation: 144
This is a function that can do it for you.
function oddEvenCounts(arr) {
const counts = {
even: 0,
odd: 0
};
arr.forEach(n => {
if(n % 2 === 0) {
counts.even++;
} else {
counts.odd++
}
});
return counts;
}
const array = [5, 3, 8, 6, 9, 1, 0, 2, 2];
console.log(oddEvenCounts(array));
Upvotes: 1
Reputation: 4568
Well, odd isn't defined. What you should do is either put odd/even in quotes (counts['odd']
) or use dot notation (counts.odd
).
Also, since odd and even aren't defined, incrementing them would result into NaN
. The initial value should instead be { odd: 0, even: 0 }
.
var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
if (number % 2 === 1) {
counts['odd']++;
} else {
counts['even']++;
}
return counts;
}, { odd: 0, even: 0 });
console.log(oddEvenCounts);
Upvotes: 9