0

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 }


Barmar
  • 741,623
  • 53
  • 500
  • 612
areh1819
  • 11
  • 1
  • 1
    The `countBy` function isn't supposed to be only `even/odd`. The callback can return any strings, and you should create an object that uses those as the keys. – Barmar Apr 04 '23 at 20:40
  • if I remove the === 'odd' or the === 'even' the odd counter gets set to 0 and the odd counter sets to 5 – areh1819 Apr 04 '23 at 21:02
  • You need to assign `callback(array[i])` to a variable. Then use that variable as the key in the result object. If the key exists, add 1 to its value. If the key doesn't exist, add it with value = 1. – Barmar Apr 04 '23 at 21:04

0 Answers0