groups Count js exercice

Groups Count JS Exercise

As someone who loves coding, I always look for new challenges to improve my skills. Recently, I came across the Groups Count JS exercise that was both challenging and fun to solve.

The exercise requires you to write a function that takes an array of integers as input and returns an object with the count of even and odd numbers in the array. Here's the code for the function:


function groupsCount(arr) {
  let evenCount = 0;
  let oddCount = 0;
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      evenCount++;
    } else {
      oddCount++;
    }
  }
  
  return { even: evenCount, odd: oddCount };
}

Explanation

The function starts by initializing two variables, evenCount and oddCount, to zero. It then loops through the input array and checks whether each number is even or odd using the modulus operator (%). If the number is even, it increments the evenCount variable, otherwise it increments the oddCount variable.

Finally, the function returns an object with two properties, even and odd, which contain the count of even and odd numbers respectively.

Usage

To use this function, simply call it with an array of integers as input. Here's an example:


const arr = [1, 2, 3, 4, 5, 6];
const result = groupsCount(arr);

console.log(result); // {even: 3, odd: 3}

As you can see, the function correctly counts the number of even and odd numbers in the input array.

Alternative Solutions

While the above solution works perfectly fine, there are other ways to solve this problem as well. One alternative solution is to use the reduce method instead of a for loop:


function groupsCount(arr) {
  return arr.reduce((acc, curr) => {
    if (curr % 2 === 0) {
      acc.even++;
    } else {
      acc.odd++;
    }
    
    return acc;
  }, { even: 0, odd: 0 });
}

This solution uses the reduce method to iterate over the input array and accumulate the count of even and odd numbers in an object.

Conclusion

The Groups Count JS exercise is a great way to improve your coding skills and learn new techniques. By solving this problem, you can practice your logic and algorithmic thinking and become a better programmer.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe