marie_antoinette
marie_antoinette

Reputation: 181

Javascript Reduce Method Creating Accumulator Object

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?

Upvotes: 4

Views: 10842

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

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

Upvotes: 11

Joe
Joe

Reputation: 82594

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;
}, {});

Upvotes: 3

Related Questions