We may frequently need to filter and display a subset of data based on a specific condition.
Let's see an example to understand this concept. Suppose we have users' data with fields such as name
, email
, isActive
, and profileUrl
. Here the isActive
field represents the status of the user, where true
means the user is currently active, and false
means the user is not active at the moment.
Our goal is to display a list of users who are currently active. In this case, we can use JavaScript’s filter() method to filter out the active users, and then we can use the map() method to render the list of active users.
Step 1. Create a new array that contains only active users:
Here the filter
method iterates through each object of the USERS
array and includes the user
object in the activeUsers
array only if the isActive
field is set to true
.
Step 2. Map over the activeUsers
array to generate JSX nodes:
Step 3. Return the mapped array of JSX nodes from the App
component: