1

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;
 }, {});
2
  • 3
    use counts.odd and counts.even instead of counts[....] or even counts["odd"] and counts["even"] Commented Sep 25, 2017 at 3:06
  • Keys have to be strings... Commented Sep 25, 2017 at 3:08

3 Answers 3

9

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

0

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}

1 Comment

Please format your code with code blocks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.