Filter a JavaScript array with JSX and the `Array.filter()` method

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we use application state to filter a list of names from a JavaScript array. When users type a search string in the Search component, the NamePicker component re-renders with the updated list of names matching the search.

Simon Vrachliotis: [0:00] Now that we have our search value passed to the NamePicker component, let's filter through the names array with the array .filter method. I'll define the filteredNames variable, and in there we'll take names, call .filter on it, and for each entry we'll check if the entry.name.includes(searchValue). This will filter out all the names that were no match.

[0:23] Now, I can replace names down here with our filteredNames array. Let's give it a try. It works! But, as you can see, if I search for logan with a lowercase l, it won't match the string. It's expecting an exact match. This is probably not the way we want the search to work.

[0:42] To mitigate this, we can normalize the strings to lowercase on both sides. Now, search with both uppercase or lowercase will match. Nice.