Filter Even with Arrow Function
Write a JavaScript function that uses an arrow function with the Array.filter() method to extract all even numbers from an array. The filter method creates a new array with all elements that pass a test implemented by the callback function.
The arrow function provides a concise syntax: (num) => num % 2 === 0. This expression checks if a number is divisible by 2 with no remainder. Arrow functions have a shorter syntax than traditional function expressions and automatically return the expression value when written without curly braces.
Array.filter() iterates through each element, passing it to the callback. If the callback returns true, the element is included in the result array. The combination of arrow functions with array methods like filter, map, and reduce is a hallmark of modern JavaScript programming.
Time complexity is O(n) where n is the array length. The filter method visits each element exactly once. Space complexity is O(k) where k is the number of even elements (at most n). The original array remains unmodified.
Edge cases include empty arrays (return empty array), arrays with no even numbers (return empty array), negative numbers, and zero (which is even). The modulo operator handles all integers correctly.
Example Input & Output
Includes zero and negatives
No even numbers
Filter even numbers
Empty array
All even numbers
Algorithm Flow

Solution Approach
Use an arrow function with filter() to select even numbers from an array. Arrow functions provide a concise syntax: n => n % 2 === 0 replaces the traditional function(n) { return n % 2 === 0; }.
Arrow functions lexically bind this, making them unsuitable for methods that need the calling context. For simple predicates like parity checking, they provide the most readable syntax.
Time O(n), Space O(n).
Best Answers
function solution(nums) {
return nums.filter(function(num) {
return num % 2 === 0;
});
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
