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?
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?
Share Improve this question asked Sep 20, 2017 at 20:38 marie_antoinettemarie_antoinette 1811 gold badge2 silver badges11 bronze badges 1-
what values are stored in the variables
even
andodd
? – Thomas Commented Sep 20, 2017 at 21:24
2 Answers
Reset to default 11The working code with ments:
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;
}, {});