Facebook Pixel

Count even numbers

JavaScript
easy
5 mins

Given an array arr of numbers, return the count of elements that are even integers (divisible by 2). The value 0 counts as even.

Examples

Input: arr = [1, 2, 3, 4] Output: 2
Input: arr = [-2, -5, -8] Output: 2
Input: arr = [0, 2, 3] Output: 2
Input: arr = [] Output: 0

Constraints

  • Input must be an array of finite numbers
  • Count only numbers that are integers and divisible by 2
  • Return false for non-array inputs
  • Return false for arrays containing non-number values
  • Return false forarrays containing NaN, Infinity, or -Infinity

Function Signature

function countEvens(arr) { // Your code here }

Test Cases

  • Base cases: empty array [], single even [ 2 ], single odd [ 1 ]
  • Mixed arrays: [ 1, 2, 3, 4 ], [ -5, 2, -3, 4 ]
  • All evens: [ 2, 4, 6 ]
  • No evens: [ 1, 3, 5 ]
  • Zeros: [ 0 ], [ 0, 0, 0 ]
  • Decimals: treat only integer values as even (e.g., 2.0 is even, 2.2 is not)
  • Invalid inputs: null, undefined, 42, '8', {}, () => {}, [1, 'a'], [NaN], [Infinity]

Companies:

Accenture
tcs
wipro
infosys
capgemini

Solve Similar questions šŸ”„

Please Login.
Please Login.