Counting Even Numbers in an Array using JavaScript

RMAG news

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
}

console.log(isEven([1, 2, 3, 4, 5])); // Should output 2

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.

Leave a Reply

Your email address will not be published. Required fields are marked *