<div>
{names.filter(name => name.includes('J')).map(filteredName => (
{filteredName}
))}
</div>
Let’s break down the code above.
First, we define our JSX inside by opening a new curly bracket inside of a <div> element. Then, we specify the array for which we want to perform the filter function on.
Because we are performing a function we open up a set of parentheses. This is where we want to set our condition for the filter: in this case, if the element in the array includes the letter ‘J’.
Did you know that you can chain array function in JavaScript, such as
filter
,
map
, and
reduce
? This can save many lines of code, although it may be difficult to understand for those new to coding.
Finally, we perform another function after the
filter
function: the
map
function. This is how we can output the array elements that match the filter condition to the actual user interface inside of
li
tags.
Let’s see the complete React component code:
import React from 'react';
const names = ['James', 'John', 'Paul', 'Ringo', 'George'];
function App() {
return (
{names.filter(name => name.includes('J')).map(filteredName => (
{filteredName}
))}
</div>
export default App;
{people.filter(person => person.age < 60).map(filteredPerson => (
{filteredPerson.name}
))}
</div>
It’s very similar to before, just with an extra step of declaring what value inside of the person object we want to filter on:
people.filter(person => person.age < 60)
See above we change the condition to compare the value of age to see if it is less than 60. That
filter
function will loop through every object in the people array and check the value of age inside each object to check if it is less than 60.
If it is, then we include it in the next step, which is to map those filtered objects out.
Let’s see the entire React component that filters an array of objects by a value inside of the object:
import React
from 'react';
const people
= [
name
: 'James',
age
: 31,
name
: 'John',
age
: 45,
name
: 'Paul',
age
: 65,
name
: 'Ringo',
age
: 49,
name
: 'George',
age
: 34,
function App() {
return (
{people
.filter(person
=> person
.age
< 60).map(filteredPerson
=> (
{filteredPerson
.name
}
))}
</div>
export default App;
Additionally, if you are getting started in React, why not check out my tutorial on how to create your first React component.
Related Posts:
👋 Hey, I'm James Dietrich
James Dietrich is an experienced web developer, educator, and founder of Upmostly.com, a platform offering JavaScript-focused web development tutorials. He's passionate about teaching and inspiring developers, with tutorials covering both frontend and backend development. In his free time, James contributes to the open-source community and champions collaboration for the growth of the web development ecosystem.