So my code is counting the counter variables correctly. What are a few easy ways I can add the keys, odd and even to the object and set their values to my counter variables? I am used to programming in C and am not experienced with objects in javascript. The Question prompt reads as follows:
Create a function
countBy
that accepts an array and a callback, and returns an object.countBy
will iterate through the array and perform the callback on each element. Each return value from the callback will be saved as a key on the object. The value associated with each key will be the number of times that particular return value was returned.
// ADD CODE HERE
function countBy(array, callback) {
let obj = {};
let oddCounter = 0;
let evenCounter = 0;
for (let i = 0; i < array.length; i++) {
if (callback(array[i]) === 'odd') {
oddCounter++;
} else if (callback(array[i]) === 'even') {
evenCounter++
}
}
return obj;
console.log(obj)
}
// Uncomment these to check your work!
function evenOdd(n) {
if (n % 2 === 0) return 'even';
else return 'odd';
}
const nums = [1, 2, 3, 4, 5];
console.log(countBy(nums, evenOdd)); // should log: { odd: 3, even: 2 }