Mastering the filter() Method in JavaScript: A Practical Application.
In this tutorial, we will learn about the filter() method, how it works, and how to use it in a real-world application. We will create a small application featuring a search box and some products, as shown below.
We will then use the filter()
method to search for a drink. For example, if we search for beetroot, we will get the following results:
As the name suggests, the filter()
method is used to sieve elements from an array that passes the condition specified. It does this by calling a function on each element, then returns only the elements that satisfy the condition in the function..
The syntax looks like this:
const filteredArray = array.filter((currentElement, index, array) => {
// Use currentElement, index, and array in your filtering logic
// Return true to keep the element in the filtered array
});
The callback function takes three parameters, namely
currentElement: The current element being iterated over.
index (optional): The index of the current element.
array (optional): The original array upon which the
filter()
method is applied.
Let's look at an example; suppose you have an array of people's ages.
const ages = [21,34,45,33,60,70,40]
Let's get the ages of people greater than or equal to 60 using the filter()
method. First, let's define a function called filterAge()
. This function will take age as a parameter. Inside the function, we will return the age whose value is greater than or equal to 60
function filterAge(age){
return(age>=60)
}
Now let's call the apply the filter()
method on the ages array and pass in the filterAge()
function as follows:
const filteredAges =ages.filter(filterAge,index,Array)
console.log(filteredAges)
Our output will look like this:
As you can see, we still have access to the index and the array arguments even though we are not using them now. So, if we omit the optional parameter, our code will look like this:
const filteredAges =ages.filter(filterAge)
console.log(filteredAges)
Using the Filter() Method in a Real-world Application
In any e-commerce store, there is always a search box at the top of the page that allows customers to search for a specific product. Let's see how we can add search capabilities using the filter()
method. We will use the following products in the application.
let products = [
{
id: 1,
description: "Beetroot Juice",
price: 10.99,
imageSrc: "https://source.unsplash.com/yIE7pZUmT_s"
},
{
id: 2,
description: "Pomegranate juice",
price: 20.49,
imageSrc: "https://source.unsplash.com/IKaFDABbfFY"
},
{
id: 1,
description: "Cocktail Juice",
price: 10.99,
imageSrc: "https://source.unsplash.com/l4OSEZZSQuQ"
},
{
id: 2,
description: "Vodka",
price: 20.49,
imageSrc: "https://source.unsplash.com/kbch-i63YTg"
},
{
id: 3,
description: "Passion Juice",
price: 15.79,
imageSrc: "https://source.unsplash.com/gBvGB7mpbjk"
},
{
id: 3,
description: "Mixed Juice",
price: 15.79,
imageSrc: "https://source.unsplash.com/ktMU5IS407s"
}
];
HTML Structure
Our HTML structure will feature a search box and a container with some products.
<div class="wrapper">
<div class="searchbox">
<input type="text" placeholder="Search product">
<button><i class="fa-solid fa-magnifying-glass"></i></button>
</div>
<div class="container">
<div class="products">
<!-- <div class="product">
<img src="https://source.unsplash.com/vxyfNhfZdbA" alt="" />
</div>
<div class="product">
<img src="https://source.unsplash.com/vy91_-RLZ2Q" alt="" />
</div> -->
</div>
</div>
</div>
The first thing will be to display the products on the page.
const productsDiv = document.querySelector('.products');
let productList = products.map((product)=>{
return `<div class="product">
<img src="${product.imageSrc}" data-id = ${product.id} alt="${product.description}">
<p>${product.description}</p>
<span> $ ${product.price}</span>
</div>`;
}).join("")
productsDiv.innerHTML = `${productList}`;
Here, we have used the map()
method to display the products. If you need a refresher on how to use the map() method,
The next step is to add an event listener that will listen for a click event on the search button and get the value from the input.
searchBtn.addEventListener("click", ()=>{
const drink = document.querySelector('.searchbox input').value
)}
Inside the event listener, we iterate over the products array and check each product's description for a keyword matching the value from the input. If true, the product is added to the filtered array.
const filteredProducts = products.filter(product=>{
return product.description.toLowerCase().includes(drink)
})
Next, we will check if the filteredProducts array is empty using length. If the length is > 0, the filter()
method has returned some results. Otherwise, no results have been returned.
searchBtn.addEventListener("click", ()=>{
const drink = document.querySelector('.searchbox input').value
const filteredProducts = products.filter(product=>{
return product.description.toLowerCase().includes(drink)
})
if(filteredProducts.length>0){
const html = filteredProducts.map(product =>{
return `<div class="product">
<img src="${product.imageSrc}"
alt="${product.description}">
<p>${product.description}</p>
<span> $ ${product.price}</span>
</div>`
}).join("")
productsDiv.innerHTML = `${html}`;
drink.innerHTML = '';
}
else{
productsDiv.textContent =`There are no results for "${drink}".`
drink.innerHTML = '';
}
})
Here, we display the filtered results on the page, and a message will be displayed if no results are found.