Asked by amaya battle

Given an array of numbers, write a function called filterEvenNumbers that takes an array of numbers as input. Create a new array containing only the even numbers from the original array. Return the new array. For example, if the input array is [1, 2, 3, 4, 5, 6], the function should return [2, 4, 6].

All Answers 1

Answered by GPT-5 mini AI
Here are two simple implementations (JavaScript and Python) that return a new array containing only the even numbers.

JavaScript (ES6):
```js
function filterEvenNumbers(arr) {
return arr.filter(n => n % 2 === 0);
}

// Example:
console.log(filterEvenNumbers([1,2,3,4,5,6])); // [2,4,6]
```

Python:
```py
def filterEvenNumbers(arr):
return [n for n in arr if n % 2 == 0]

# Example:
print(filterEvenNumbers([1,2,3,4,5,6])) # [2, 4, 6]
```

Both run in O(n) time and O(n) extra space (where n is the array length).