Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 8

Array Method Utility

Recommended resources

Hello! Welcome to the final lesson in our module on modern JavaScript array methods.

In our last session, we saw how to chain methods like filter, map, and reduce to create clean, readable data pipelines. You learned to think of data processing as a flow: starting with a raw array, removing unwanted items, transforming the remaining ones, and finally aggregating a result.

Today, we'll put all of that theory into practice. You're going to build a mini data filtering and sorting utility, a small but powerful project that synthesizes everything you've learned in this module. This project is a direct stepping stone toward your goal of building an e-commerce site, as product filtering is a core feature of any online store.

By the end of this lesson, you will have built a functional UI that can:

  • Display a list of products from a data array.
  • Filter products by category using checkboxes.
  • Filter products by name using a search input.
  • Sort the filtered products by price.

1. The Goal: A Dynamic Product List

Before we dive into the code, let's look at what we're aiming to build. The image below shows a typical product filtering interface. This is the kind of functionality we'll create with vanilla JavaScript and the array methods you've mastered.

Product Filter and Search UI Example
A visual example of a product filtering interface, combining category selection, search, and a product display area.

2. Setting the Stage: Rendering the Products

First, we need a basic HTML structure and a starting array of product data. For this project, we'll work with a pre-defined array of products, much like you might receive from a Laravel API endpoint.

Our initial task is to take this array and dynamically render each product on the page.

Tailwind & JavaScript Project - Products Filtering UI

The video 'Tailwind & JavaScript Project - Products Filtering UI' by Traversy Media provides an excellent walkthrough of building this exact type of utility. We'll start by watching how to set up the project and render the initial list of products.

Watch from 00:19:26 to 00:30:49. The key takeaways are: Setting up data and selecting DOM elements (19:26 - 22:13): Notice how he prepares the product data and uses getElementById and querySelectorAll to get handles on the UI elements. Rendering products (22:13 - 30:49): Pay close attention to how he uses products.forEach() to loop over the data, document.createElement() to create a div for each product, and .innerHTML with template literals to populate it with product details.

As you saw in the video, the core logic for rendering is a forEach loop. For each product in our array, we create an HTML element, populate it with the product's data, and append it to our main product container. This is a fundamental pattern for displaying data from an API.


3. The Core Logic: Filtering by Category and Search

Now for the main event. We need to create a single function that handles all filtering logic. This function will run whenever a user clicks a category checkbox or types in the search box. It will check the current filter criteria, decide which products to show, and update the UI accordingly.

Tailwind & JavaScript Project - Products Filtering UI

Let's continue with the Traversy Media video. This next section is the heart of our lesson. It demonstrates how to combine array methods to implement the filtering logic.

Watch from 00:35:33 to 00:45:16. Focus on the filterProducts function and break down its steps: Getting the search term: Simple .value.trim().toLowerCase(). Getting checked categories: This is a fantastic chain: Array.from(checkboxes).filter(cb => cb.checked).map(cb => cb.id). This pipeline converts the NodeList of checkboxes to an array, filters it down to only the checked ones, and then maps it to an array of their IDs (the category names). Matching logic: For each product, he checks if it matches the search term AND the selected categories. Updating the UI: He adds or removes a 'hidden' class to show or hide the product elements.

Let's break down that filterProducts function. It's a great example of declarative programming.

// A simplified version of the logic from the video

// 1. Get the current filter criteria
const searchTerm = searchInput.value.trim().toLowerCase();

const checkedCategories = Array.from(allCategoryCheckboxes)
  .filter(checkbox => checkbox.checked)
  .map(checkbox => checkbox.id);

// 2. Loop through each product element to decide if it should be shown
productElements.forEach(element => {
  const productName = element.dataset.name.toLowerCase(); // Assuming product name is stored in a data attribute
  const productCategory = element.dataset.category; // Assuming category is in a data attribute

  // 3. Define the matching conditions
  const matchesSearch = productName.includes(searchTerm);
  
  // If no categories are checked, show all. Otherwise, check if the product's category is in the list.
  const matchesCategory = checkedCategories.length === 0 || checkedCategories.includes(productCategory);

  // 4. Show or hide the element
  if (matchesSearch && matchesCategory) {
    element.classList.remove('hidden');
  } else {
    element.classList.add('hidden');
  }
});

This approach of toggling classes is efficient for a small number of items already in the DOM. An alternative, which is more scalable and often used in frameworks like React, is to filter the data array first and then re-render the entire list based on the filtered data.


4. Adding a Final Touch: Sorting

The video doesn't include sorting, so let's add it ourselves. This will complete our utility. We'll add a dropdown (<select>) to sort by price (ascending or descending).

First, we need to modify our approach. Instead of just showing/hiding existing elements, we need to:

  1. Filter the original products array.
  2. Sort the resulting filtered array.
  3. Render the sorted, filtered array to the DOM.

Let's look at how to implement the sorting part. The .sort() method is what we need here, and for sorting objects, we must provide a custom comparator function.

Filter, Sort, and Search Arrays with JavaScript

This article from Server Side Up provides a clear explanation of how to use .sort() with custom comparators for both numbers and objects.

Read the section titled 'Sorting Arrays'. Pay attention to the 'Sort Descending' and 'Sort Array of Objects' examples. The key is the comparator function (a, b) => a.property - b.property for numerical sorting.

Now, let's combine filtering and sorting into a single, powerful function.

function updateDisplayedProducts() {
  const searchTerm = searchInput.value.trim().toLowerCase();
  const sortValue = sortSelect.value; // e.g., 'price-asc', 'price-desc'

  const checkedCategories = Array.from(allCategoryCheckboxes)
    .filter(checkbox => checkbox.checked)
    .map(checkbox => checkbox.id);

  // 1. FILTER the data
  let filteredProducts = products.filter(product => {
    const matchesSearch = product.name.toLowerCase().includes(searchTerm);
    const matchesCategory = checkedCategories.length === 0 || checkedCategories.includes(product.category);
    return matchesSearch && matchesCategory;
  });

  // 2. SORT the filtered data
  if (sortValue === 'price-asc') {
    filteredProducts.sort((a, b) => a.price - b.price);
  } else if (sortValue === 'price-desc') {
    filteredProducts.sort((a, b) => b.price - a.price);
  }
  
  // 3. RENDER the final list
  productsWrapper.innerHTML = ''; // Clear the current list
  filteredProducts.forEach(product => {
    // Code to create and append the product element, as seen in the video
    const productElement = createProductElement(product); // Assume this function exists
    productsWrapper.appendChild(productElement);
  });
}

// Add event listeners
searchInput.addEventListener('input', updateDisplayedProducts);
filtersContainer.addEventListener('change', updateDisplayedProducts);
sortSelect.addEventListener('change', updateDisplayedProducts);

This updateDisplayedProducts function is a perfect demonstration of a data pipeline. It takes raw data, pipes it through a filter, then a sorter, and finally renders the result. This pattern is fundamental to building interactive data-driven applications.


Conclusion

Congratulations! You've successfully designed a data filtering and sorting utility by combining the array methods you've learned throughout this module. This project isn't just an exercise; it's a foundational piece of the e-commerce application you aim to build.

Key Takeaways:

  • You can build complex, interactive features using a combination of filter, map, sort, and forEach.
  • Chaining methods like filter and map creates clean and readable pipelines for preparing data (e.g., getting selected checkbox values).
  • A common, powerful pattern for dynamic UIs is: Filter data -> Sort data -> Render UI.
  • You can handle multiple user inputs (search, checkboxes, sorting) in a single, cohesive function that updates the view.

This lesson concludes our first module on mastering modern array methods. You now have a solid foundation for manipulating data collections in JavaScript.

In our next lesson, we will begin Module 2: Core ES6+ Syntax and Patterns. We'll start by tackling a topic you've mentioned can be tricky: the this keyword, and specifically how its behavior differs in traditional functions versus modern arrow functions.