Filter Even Numbers
Filter only even numbers from an array.
Array filtering with filter() is essential for data processing and manipulation. This exercise teaches you functional programming concepts, predicate functions, and how to transform arrays based on conditions.
📚 Concepts & Theory
Filtering arrays based on conditions is a core operation in JavaScript. The filter() method creates a new array with elements that pass a test, embodying functional programming principles.
Understanding Array Filtering:
Method 1: filter() - Most Functional
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);
// Returns: [2, 4, 6]
Method 2: Traditional for Loop
const evens = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evens.push(numbers[i]);
}
}
Method 3: forEach() with Push
const evens = [];
numbers.forEach(num => {
if (num % 2 === 0) evens.push(num);
});
How filter() Works:
- Creates a new array (doesn't modify original)
- Calls callback function for each element
- If callback returns
true, includes element - If callback returns
false, excludes element
num % 2 === 0 // Modulo operator returns remainder
// Even numbers have remainder 0 when divided by 2
Functional Programming Benefits:
- Immutability: Original array unchanged
- Declarative: Describes what you want, not how
- Chainable: Can combine with map(), reduce(), etc.
- Readable: Intent is clear from method name
const sum = numbers
.filter(n => n % 2 === 0)
.reduce((acc, n) => acc + n, 0); 🎯 Your Challenge
Write filterEven that returns only even numbers.
📝 Starter Code
function filterEven(arr) {
// Your code here
}
console.log(filterEven([1, 2, 3, 4, 5, 6]));
- Use the filter() method to create a new array
- The callback function should return true for elements you want to keep
- Use the modulo operator % to check for even numbers
- Even numbers have remainder 0 when divided by 2
- filter() doesn't modify the original array
Solution
function filterEven(arr) {
return arr.filter(num => num % 2 === 0);
}
console.log(filterEven([1, 2, 3, 4, 5, 6]));
Explanation
This solution uses the filter() method with an arrow function that tests each number for evenness using the modulo operator (%). The expression num % 2 === 0 returns true for even numbers (remainder is 0) and false for odd numbers. filter() creates a new array containing only elements where the callback returned true, leaving the original array unchanged. This is the most idiomatic JavaScript approach. Time complexity: O(n). Space complexity: O(k) where k is the number of even numbers.
⚠️ Common Mistakes to Avoid
- Using map() instead of filter() (map transforms all elements)
- Forgetting to return from filter callback
- Modifying the original array
- Using = instead of === for comparison
- Confusing filter logic (thinking it removes instead of keeps matching elements)