DEV Community

ae95medina
ae95medina

Posted on

The Power of Filter()

array.prototype.filter ()

The filter() method is a method used on arrays, in which it will create a new array with all the elements that pass a test provided by a function. This method does not execute the function for empty elements, nor does it change the original array1. The syntax for the filter method goes as follows:

array.filter(callback(element, index, arr), thisValue)
Enter fullscreen mode Exit fullscreen mode

There are five parameters that are accepted for the filter method. Two parameters are required (default parameters) and the remaining three parameters are optional (optional parameters). There must be a function(or callback) set as a parameter. The function will be running for each element of the array. The current element being passed is also needed. The index, array, and value of the current element are all optional parameters 3.

What are default parameters and how do they work?

Default parameters allow named parameters to be initialized with default values if no value or undefined is passed4. In JavaScript, a function's parameters will default to undefined, but it can be useful to set a different value. In ES2015, a new concept was added where you can assign a default value in the function head4.

What are optional parameters and how do they work?

An optional parameter is always defined at the end of the list, after the default parameters. Usually, when no parameters are passed, undefined will be passed in its place2. When using optional parameters, you can define a default value. Optional parameters are most useful when simplifying code.

Filter() Example 1

Let's start with a simple way to use the filter method.


const numbers = [-3, 2, -1, 17, 0]

const filtered = numbers.filter(function(value){
return value >= 0
});

console.log(filtered)
[2, 17, 0]
Enter fullscreen mode Exit fullscreen mode

In this example, the goal was to grab any number from the original array that is either greater than or equal to zero. Passing that element through the filter, the filter function was ran to grab all numbers that match the request.

Filter() and DOM Manipulation

Filter can also be a very powerful method in DOM Manipulation. For example, I created an application that represents a workout planner The Workout Planner. The Planner has listed workouts in its library on the main page shown below a form.
Workout Main Page
The application has two inputs: one to choose a primary muscle to work out and a second input for an optional secondary workout. My goal for the project was to create an application that can iterate through all the workout cards I have created and filter the cards accordingly based on the factors selected in the two inputs. The inputs are based on what you'd like to target for the day and after choosing your option(s), the cards will re-display below, only showing cards related to your choices. The filter method is used as follows for the primary selection:

document.addEventListener("change", event =>{
    if(event.target.matches("#primary")){
        const filterWorkouts = workouts.filter(workout => workout.target === event.target.value)
        document.getElementById("workout_collection").innerHTML= "";
        filterWorkouts.forEach(workout=> {
        showWorkouts(workout)
       }) 
    }
Enter fullscreen mode Exit fullscreen mode

In this code, I am targeting the event that occurs when an input is selected, I am matching the input with data from JSON "workout.target", which is the target muscle group, and I am filtering and displaying only the cards that match that muscle target. With that a specific workout can be created, whatever you choose! Here is an example below:

Workout Filter Example
Generally, some people like to combine two muscle groups. This is why i have a second input. The second input is its own separate filter, and will add the secondary muscle group to the end of your workout. The code is as follows:

document.addEventListener("change", event =>{
        if(event.target.matches("#secondary")){
          const filterWorkouts = workouts.filter(workout => workout.target === event.target.value)
           filterWorkouts.forEach(workout=> {
            showWorkouts(workout)
           })    
        }
        })
Enter fullscreen mode Exit fullscreen mode

For example, if I wanted to work out chest and triceps for today, chest being my primary, and triceps being secondary, the filter will show chest cards and tricep cards below.

The filter() method is very dynamic in its use. It can filter simple arrays or it can be a powerful tool in DOM Manipulation and application creations. When incorporating the method through my project, I was ecstatic to see the method unfold before my eyes. In using the filter method(), I became more understanding about array methods and how to use those methods. I learned how they can be useful for manipulating and simplifying my code and the circumstances for when it can be useful to target certain features of my code.

Top comments (0)