DEV Community

Ticha Godwill Nji
Ticha Godwill Nji

Posted on • Updated on

Counting Even Numbers in an Array using JavaScript

In JavaScript, it's often necessary to perform operations on arrays efficiently. One common task is counting the number of even numbers within an array. The isEven function provided below accomplishes this task by iterating through the array and incrementing a counter whenever it encounters an even number.

function isEven(arr) {
    var count = 0; // Initialize a counter to keep track of even numbers

    // Iterate through the array
    for (var i = 0; i < arr.length; i++) {
        // Check if the current element is even
        if (arr[i] % 2 === 0) {
            count++; // Increment the counter if the element is even
        }
    }

    return count; // Return the total count of even numbers
}
Enter fullscreen mode Exit fullscreen mode
console.log(isEven([1, 2, 3, 4, 5])); // Should output 2

Enter fullscreen mode Exit fullscreen mode

Analysis

  • Efficiency: The time complexity of this function is O(n), where n is the length of the input array. This is because it iterates through the array once, performing a constant-time operation (modulus) on each element.

  • Space Complexity: The space complexity of this function is O(1) because it only uses a constant amount of additional memory regardless of the size of the input array. The only variable it declares is count, which stores the count of even numbers.

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
arr.filter(x=>1&x^1).length
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

How about an option that's both more generic and avoids allocating a new array:

count = fn => arr => arr.reduce((c,v) => c+(!!fn(v)),0)
count_even = count(x=>1&x^1)
console.log(count_even([1, 2, 3, 4, 5]))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gloomweaver profile image
Kirill Khramkov

With developer.mozilla.org/en-US/docs/W...

Iterator.from(array)
  .filter((x) => x % 2 == 0)
  .reduce((acc) => acc + 1, 0);
Enter fullscreen mode Exit fullscreen mode