How to Filter Arrays in React
Filtering is a process that creates an array filled with all array elements that pass a test. In this article we’re going to see how to filter arrays in React.
Table of Contents
Filter Single Array
Let’s assume an array:
const students = ['Obydul', 'Kabir', 'Hussain', 'Kamrul'];
Now we want to find students that match with the condition:
{students.filter(student => student.includes('K')).map(filteredStudent => (
<li>
{filteredStudent}
</li>
))}
This condition will print all student names that contain character “K“. The final code looks like:
App.js
import React from 'react';
const students = ['Obydul', 'Kabir', 'Hussain', 'Kamrul'];
function App() {
return (
<ul>
{students.filter(student => student.includes('K')).map(filteredStudent => (
<li>
{filteredStudent}
</li>
))}
</ul>
);
}
export default App;
Filter Multidimensional Array
Let’s assume a multidimensional array:
const students = [
{
'id': 1,
'name': 'Obydul',
'age': 25
},
{
'id': 2,
'name': 'Kabir',
'age': 24
},
{
'id': 3,
'name': 'Hussain',
'age': 30
},
{
'id': 4,
'name': 'Kamrul',
'age': 35
},
];
From this array, we want to get those students under the age of 30. So, the condition should be:
{students.filter(student => student.age < 30).map(filteredStudent => (
<tr>
<td>{filteredStudent.id}</td>
<td>{filteredStudent.name}</td>
<td>{filteredStudent.age}</td>
</tr>
))}
The complete React component code:
App.js
import React from 'react';
const students = [
{
'id': 1,
'name': 'Obydul',
'age': 25
},
{
'id': 2,
'name': 'Kabir',
'age': 24
},
{
'id': 3,
'name': 'Hussain',
'age': 30
},
{
'id': 4,
'name': 'Kamrul',
'age': 35
},
];
function App() {
return (
<div>
<table className="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
{students.filter(student => student.age < 30).map(filteredStudent => (
<tr>
<td>{filteredStudent.id}</td>
<td>{filteredStudent.name}</td>
<td>{filteredStudent.age}</td>
</tr>
))}
</table>
</div>
);
}
export default App;
That’s it. Thanks for reading.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.