The JavaScript Filter Method

Create a real-time search filter in react

Introduction

The JavaScript filter method is one of the higher order functions that allows use to filter content based on a condition that has been set. Today, we will take a look at how to implement it in our code as well as look at some "Real-World examples" of how it could be used as means to search through an array of content.

Getting Started

The .filter() method is a higher order function that can be called on any array or object -- see below:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.filter();

It takes in a function as its argument and also has a return value which is an array that contains the elements that passes the condition implemented. The filter method essentially loops through every item in the array that it is called on and checks the current iteration on a parameter that is set. Like state previously, if the condition is met, then the added to the array that is returned by the function. The example below shows us using the filter method to remove the number 4 from the array called "arr".

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.filter((number) => number != 4);

The return value here will be [1,2,3,5,6,7,8,9,10]

Example 2

For another example,more interesting -- Given a array of objects, where each object represents a student that has taken a test, return the names of the students that scored at least an 80% on the test. We can use the array filter method to do this. The object contains two keys -- the students name and their grade {Name:"", Grade:0}.

const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];

Since we are given a array of objects, we can use the filter method to loop through the entire array and check if the current student's grade is greater or equal to 80%. It looks something like this:

const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];

students.filter((student) => {
  if (student.Grade >= 80) {
    return student.Name;
  }
});

A short hand for this would be and we can store the return value in a variable so that we can use it later. The following look something like this:

const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];

const stuAbove80 = students.filter((student) => student.Grade >= 80);

The Fun Stuff -- Add a search field to your web application

A common feature in most applications that have large amounts of scrollable content is a search field -- users enjoy the experience of being able to quickly search for the content they want to find since it saves them time in the end. This feature can be accomplished in many ways but today we will be using the javascript filter method add a search feature to the students array we have been working with, this time we will be searching for a specific student by name. The advantage of using the filter method is that we can filter out the content as the user types -- this is best described when you are searching for something to watch on netflix.

You can do this with vanilla JavaScript, however, today we will be using a library such as react to create our UI.

Let's pretend that we made an api request and this is the data you got back:

const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];

We are storing it in a variable called students so we can use it later on. Here is just some boiler code to get all the boring stuff out of the way. This just has an input field that is connected to a state variable and a component that is showing all the student name with their associated grades.

import react from "react";

const App = () => {
  import { useState } from "react";
  const students = [
    {
      Name: "John",
      Grade: 90,
    },
    {
      Name: "Sarah",
      Grade: 95,
    },
    {
      Name: "Jane",
      Grade: 80,
    },
    {
      Name: "Julie",
      Grade: 79,
    },
  ];

  const [searchTerm, setSearchTerm] = useState("");
  return (
    <div>
      <input
        type="text"
        onChange={(e) => setSearchTerm(e.target.value)}
        defaultValue={searchTerm}
      />

      {students.map((student) => (
        <p>
          students Name:{student.Name} and their grade: {student.Grade}
        </p>
      ))}
    </div>
  );
  export default App;
};

To add the search feature, we can filter through the students array and return a list of students objects with names that match the search term.

students.filter((student)=>{
          if (searchTerm==""){
              return student
          }
          elif (student.Name.toLowerCase().includes(searchTerm.toLowerCase())){
              return student
          }
          return null;

      })

When the search bar is empty, we want to display every object in the data holder variable so we can just return every member without filtering. Now it may seem counter-intuitive but to computers "A" is not the same as "a". To that same extent "John" is not the same a "john". So that we don't run into this issue we are going to convert search term and the Name to lower case and then check if the search term includes the Name. If it does then the current student object is going to get added to the list.

We can then map through this array that is returned from filter to display the students name and grade using the component we created. The final code should look something like below:

import react from "react";

const App = () => {
  import { useState } from "react";
  const students = [
    {
      Name: "John",
      Grade: 90,
    },
    {
      Name: "Sarah",
      Grade: 95,
    },
    {
      Name: "Jane",
      Grade: 80,
    },
    {
      Name: "Julie",
      Grade: 79,
    },
  ];

  const [searchTerm, setSearchTerm] = useState("");
  return (
    <div>
      <input
        type="text"
        onChange={(e) => setSearchTerm(e.target.value)}
        defaultValue={searchTerm}
      />

      {students.filter((student)=>{
          if (searchTerm==""){
              return student
          }
          elif (student.Name.toLowerCase().includes(searchTerm.toLowerCase())){
              return student
          }
          return null;

      }).map((student) => (
        <p>
          students Name:{student.Name} and their grade: {student.Grade}
        </p>
      ))}
    </div>
  );
  export default App;
};

Now that this is complete, we have a way to search for a student by looking up Name using a javascript function that we created!

Question for you

Now knowing this, here's a question for you -- how else can we implement the filter method?