DEV Community

loading...
Cover image for How to Implement filtering functionality in your application

How to Implement filtering functionality in your application

myogeshchavan97 profile image Yogesh Chavan ・4 min read

Let's say we have an application where we want to filter the data based on some criteria like size, color, price and so on.

In this article, we will see how we can achieve that.

Suppose, we have the following list of products:

const products = [
  { name: 'Macbook Air', price: '180000', ram: 16 },
  { name: 'Samsung Galaxy M21', price: '13999', ram: 4 },
  { name: 'Redmi Note 9', price: '11999', ram: 4 },
  { name: 'OnePlus 8T 5G', price: '45999', ram: 12 }
];
Enter fullscreen mode Exit fullscreen mode

and for filtering, we have two dropdowns one for sorting by various criteria like price and ram and the other dropdown is for the order of sorting like descending or ascending.

Take a look below codepen:

The displayProducts function in the above code, loops through the products array and generates HTML to be displayed using template literal syntax to display it inside the products div.

const displayProducts = (products) => {
  let result = "";

  products.forEach(({ name, price, ram }) => {
    result += `
     <div class="product">
      <div><strong>Name:</strong><span>${name}</span></div>
      <div><strong>Price:</strong><span>${price}</div>
      <div><strong>Ram:</strong><span>${ram} GB</div>
     </div>
    `;
  });

  container.innerHTML = result;
};
Enter fullscreen mode Exit fullscreen mode

Let's add the filtering functionality.

To handle on change of the Sort By dropdown, let's add the event handler for that.

sortByDropdown.addEventListener('change', () => {
  // some code
};
Enter fullscreen mode Exit fullscreen mode

We have already defined the reference of all the required elements at the top in the codepen.

const sortByDropdown = document.querySelector(".sort-by");
const sortOrderDropdown = document.querySelector(".sort-order");
const container = document.querySelector(".products");
Enter fullscreen mode Exit fullscreen mode

Now, lets add the sorting logic:

sortByDropdown.addEventListener("change", () => {
  const sortByValue = sortByDropdown.value; // price or ram value
  const sortOrderValue = sortOrderDropdown.value; // asc or desc value

  const sorted =
    sortOrderValue === "desc"
      ? descendingSort(sortByValue)
      : ascendingSort(sortByValue);

  displayProducts(sorted);
});
Enter fullscreen mode Exit fullscreen mode

Here, we're checking the value of the second dropdown. If it's desc we're calling the descendingSort function(which we're yet to define) otherwise we're calling the ascendingSort function by passing the first dropdown value whether to sort by price or ram.

Then we're passing that result to the displayProducts function so it will update the UI with that sorted products.

Now, let's add the descendingSort and ascendingSort functions.

const ascendingSort = (sortByValue) => {
  return products.sort((a, b) => {
    if (a[sortByValue] < b[sortByValue]) return -1;
    if (a[sortByValue] > b[sortByValue]) return 1;
    return 0;
  });
};

const descendingSort = (sortByValue) => {
  return products.sort((a, b) => {
    if (a[sortByValue] < b[sortByValue]) return 1;
    if (a[sortByValue] > b[sortByValue]) return -1;
    return 0;
  });
};
Enter fullscreen mode Exit fullscreen mode

Here, we're using the comparator function for the array sort function.

As you know, If we have an object like this:

const product = { name: 'Macbook Air', price: '180000', ram: 16 };
Enter fullscreen mode Exit fullscreen mode

then we can access its properties using two ways

  1. using product.name
  2. using product['name']

As we're having dynamic value of sortByValue variable, we're using the 2nd way inside the sort function to get the product value(a[sortByValue] or b[sortByValue]).

*To sort in ascending order: *

  • If the first value to be compared is alphabetically before the second value, a negative value is returned.
  • If the first value to be compared is alphabetically after the second value, a positive value is returned.
  • If the first and second value is equal, zero is returned.

Which will automatically sort the array in ascending order.

*To sort in descending order: *

  • If the first value to be compared is alphabetically before the second value, a positive value is returned.
  • If the first value to be compared is alphabetically after the second value, a negative value is returned.
  • If the first and second value is equal, zero is returned.

Which will automatically sort the array in descending order.

If you're not familiar with how sorting works for the comparator function, check out my this article to better understand how sorting works in JavaScript.

Now, we want to trigger the sorting functionality, when we change the sort order dropdown so let's add an event handler for that also.

sortOrderDropdown.addEventListener("change", () => {
  const event = new Event("change");
  const sortByValue = sortByDropdown.value;

  if (sortByValue) {
    sortByDropdown.dispatchEvent(event);
  }
});
Enter fullscreen mode Exit fullscreen mode

Here, we have added the if condition because we don't want to sort the products when the sort by dropdown is not selected.

Check out the below codepen for final working code:


If you don't want to write your own sorting logic, you can use the orderBy method provided lodash which is a very popular utility library.

If you're not familiar with lodash and the powerful functions provided by the library check out my this article for an introduction to its various useful methods.

Following is the codepen updated with the orderBy method:

In the above codepen, we have added the orderBy method on change of the Sort by dropdown like this:

const sorted = _.orderBy(products, [sortByValue], sortOrderValue);

displayProducts(sorted);
Enter fullscreen mode Exit fullscreen mode

and removed both the ascendingSort and descendingSort functions.

For the orderBy method, we have provided

  • the array to sort as first parameter
  • the property from the object based on which we need to sort(price or ram) as the second parameter
  • the sort order (asc or desc) as the third parameter

That’s it for today. Hope you learned something new today.

Don’t forget to subscribe to get my weekly newsletter with amazing tips, tricks, and articles directly in your inbox here.

Discussion

pic
Editor guide