JavaScript Filter
JavaScript Filter
If you are working with arrays in JavaScript, you might find that you often need to filter out certain elements based on a specific condition. This is where the filter()
method comes in handy.
Let's say for example that you have an array of numbers:
const numbers = [1, 2, 3, 4, 5];
If you wanted to filter out all the even numbers from this array, you could use the filter()
method like so:
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // [2, 4]
This code will create a new array called evenNumbers
that only contains the elements from the original numbers
array that pass the condition of being divisible by 2 with no remainder (i.e. even numbers).
How does it work?
The filter()
method takes a callback function as its argument. This callback function is applied to each element in the array, and should return either true
or false
depending on whether the element should be included in the new filtered array or not.
In the example above, we used an arrow function to define our callback function:
number => number % 2 === 0
This function takes a single argument (which represents each element in the array) and returns true
if the number is even (i.e. divisible by 2 with no remainder), or false
otherwise.
Finally, we assigned the filtered array to a new variable called evenNumbers
using the const
keyword.
Other ways to filter arrays
While the filter()
method is a powerful tool, there are other ways to achieve the same result.
For example, you could use a traditional for
loop:
const evenNumbers = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evenNumbers.push(numbers[i]);
}
}
console.log(evenNumbers); // [2, 4]
This code achieves the same result as our previous example, but uses a for
loop and the push()
method to manually build the evenNumbers
array.
You could also use the reduce()
method:
const evenNumbers = numbers.reduce((acc, number) => {
if (number % 2 === 0) {
acc.push(number);
}
return acc;
}, []);
console.log(evenNumbers); // [2, 4]
This code uses the reduce()
method to build the evenNumbers
array by applying a callback function to each element in the original numbers
array.
The callback function takes two arguments: an accumulator (which starts as an empty array) and the current element in the array. If the current element is even, it is added to the accumulator array using the push()
method. Finally, the accumulator array is returned.
While these methods all achieve the same result, the filter()
method is generally considered the most concise and readable solution.