My filter function
Now that we've explored the utilisation of the filter method in JavaScript, let's delve into the write of our own filter
function.
To maintain consistency with our approach, we'll design our filter function as a standalone function that takes an array and a callback as parameters:
function myFilter(array, filterCallback) {
// Implementation goes here
}
Now, let's break down the functionality of our filter function. As with map, filter creates a new array to store the elements that meet a certain condition. Here's the initial structure:
function myFilter(array, filterCallback) {
const newArray = [];
/*
other code
...
*/
return newArray;
}
The core of the filter method is determining which elements to include in the new array. This is where the callback comes into play. For each item in the array, the callback is executed, and if it returns true, the item is added to the new array:
function myFilter(array, filterCallback) {
const newArray = [];
for (let item of array) {
const isAccepted = filterCallback(item)
if (isAccepted) {
newArray.push(item);
}
}
return newArray;
}
Or we can evaluate the output of the callback directly in the condition like this:
function myFilter(array, filterCallback) {
const newArray = [];
for (let item of array) {
if (filterCallback(item)) {
newArray.push(item);
}
}
return newArray;
}
However, just like with map, the callback for filter can take three parameters: the current item, its index, and the array. Let's enhance our function to accommodate these parameters:
function myFilter(array, filterCallback) {
const newArray = [];
for (let index = 0; index < array.length; index++) {
if (filterCallback(array[index], index, array)) {
newArray.push(array[index]);
}
}
return newArray;
}
This implementation allows the callback to make decisions based not only on the item itself but also on its position in the array or the array as a whole, just like we saw it in the last chapter.
Now, you can use your myFilter function to create a new array containing only the elements that satisfy a given condition. Test it with different arrays and callback functions to explore its versatility.
Understanding the inner workings of fundamental array methods like filter provides a solid foundation for mastering JavaScript programming. Join me in the next chapter, where we'll uncover the intricacies of yet another powerful array method.
Happy coding! ๐๐
Subscribe to my newsletter
Read articles from Rayane TOKO directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Rayane TOKO
Rayane TOKO
๐จโ๐ป Computer Scientist | ๐ Physicist Enthusiast ๐ก Always exploring new technologies and seeking to bridge the gap between science and technology.