var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
  if (isOdd(number)) {
    counts[odd]++;
  } else {
    counts[even]++;
  }
}, {});
I am looking for the bug in this bit of code (still learning the reduce method ;)) –– where am I going wrong?
The working code with comments:
var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
function isOdd(n) {
  return !!(n % 2);
}
var oddEvenCounts = numbers.reduce(function(counts, number) {
  if (isOdd(number)) {
    counts.odd++; // use dot notation or ['odd']
  } else {
    counts.even++;  // use dot notation or ['even']
  }
  
  return counts; // return the accumulator
}, { odd: 0, even: 0 }); // set the initial values of odd and even
console.log(oddEvenCounts);You can shorten the code a bit by using the brackets notation and the ternary operator:
var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
function isOdd(n) {
  return !!(n % 2);
}
var oddEvenCounts = numbers.reduce(function(counts, number) {  
  counts[isOdd(number) ? 'odd' : 'even']++;
  
  return counts;
}, { odd: 0, even: 0 });
console.log(oddEvenCounts);Return your accumulator:
var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
  if (isOdd(number)) {
    counts[odd]++;
  } else {
    counts[even]++;
  }
  return counts;
}, {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With