How to Filter Even Numbers from an Array Using JavaScript
When faced with the task of filtering out only the even numbers from an array of numbers, JavaScript provides a powerful tool in the form of the filter() method. This method creates a new array with all numbers that pass a given test, which in this case is checking if a number is even.
For example, let's consider an array like [1, 2, 3, 4, 5, 6, 7, 8]. If we apply the filter() method to this array and test each number for being even, the resulting array would be [2, 4, 6, 8].
How Does the filter() Method Work?
The filter() method acts on each element of the array, applying a specified function and returning a new array with only the elements that pass the test. In this case, we want to check if the number is even using the condition 'num % 2 === 0'.
Here's a sample function using filter() to extract even numbers:
function noOdds(arr) {
return arr.filter(num => num % 2 === 0);
}
In this function, we pass an array as a parameter and then use the filter() method to create a new array containing only the even numbers from the original array. Each number is checked to see if it is divisible by 2 without a remainder (i.e., if num % 2 === 0), and only those that meet this condition are included in the new array.
For instance, if we call the function noOdds() with the array [1, 2, 3, 4, 5, 6, 7, 8], it will return [2, 4, 6, 8] – the even numbers from the original array.
By using the filter() method in JavaScript, you can easily extract specific elements from an array based on a certain criteria, making it a versatile and efficient solution for tasks like filtering out even numbers.