React Filter Array
Want to filter an array in React js? Just use the Array.prototype.filter() method that is available in javascript to do that. React js is a javascript library to build user interfaces (UI). I’ll share code examples to show you how to filter arrays in Reactjs.
Filter array in javascript
The Array.prototype.filter() method is an iterative method. It calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a truthy value. Array elements that do not pass the callbackFn test are not included in the new array.
const fruits = ['Lemons', 'Strawberries', 'Oranges', 'Blackberries', 'Apples', 'Pomegranate']; const result = fruits.filter(fruit => fruit.length < 8); console.log(result); // expected output: Array ["Lemons", "Oranges", "Apples"]
React: filter array of strings
To filter an array in React will use the same filter() method we used above. However, there is a slight syntax requirement if you are using the method inside JSX. For example, you want to display a filtered list of fruits that meet the condition of having a character length that’s less than 8. You want to render that inside a <li>. Let’s take a look at the code example below
import React from 'react';
const fruits = ['Lemons', 'Strawberries', 'Oranges', 'Blackberries', 'Apples', 'Pomegranate'];
function App() {
return (
<div>
<ul>
{fruits.filter(fruite => fruit.length < 8).map(filteredFruit => (
<li>
{filteredFruit}
</li>
))}
</ul>
</div>
);
}
export default App;
In order to use any javascript expression inside JSX we need to wrap that with curly braces. That’s why I am wrapping the filter() call inside two curly braces.
Array.prototype.map() creates a new array populated with the results of calling a provided function on every element in the calling array. In this case, it will return an array of <li> fruit </li>
React: filter array of objects
A common example in React is to filter an array of objects. For example, we have an array of objects fruits, each element in this array is an object of two properties (name and totalSugar). The requirement here is to filter the fruits array and display only the fruits that have totalSugar of less than 10. Render the result array in <li>.
import React from 'react';
const fruits = [
{
name: 'Lemons',
totalSugar: 2.5,
},
{
name: 'Strawberries',
totalSugar: 5.8,
},
{
name: 'Oranges',
totalSugar: 9.2,
},
{
name: 'Blackberries',
totalSugar: 8.1,
},
{
name: 'Apples',
totalSugar: 13.3,
}
];
function App() {
return (
<div>
{fruits.filter(fruit => fruit.totalSugar < 10).map(filteredFruit => (
<li>
{filteredFruit.name}
</li>
))}
</div>
);
}
export default App;
I am passing the condition fruit.totalSugar < 10 to the callback fn of the filter() method since each element in the array is an object.
