React Js Skip Element of Array in .map() Function
_Function.jpg)




Thanks for your feedback!
Your contributions will help us to improve service.
xxxxxxxxxx
<script type="text/babel">
const { useState, useEffect } = React;
function App() {
const data = [
{ name: "Apple", color: "red" },
{ name: "Banana", color: "yellow" },
{ name: "Kiwi", color: "green" },
{ name: "Orange", color: "orange" },
{ name: "Grapes", color: "purple" },
];
const excludedFruits = ["Kiwi", "Grapes"]; // Names of fruits to skip
const result = data.map(fruit => {
if (excludedFruits.includes(fruit.name)) {
// Skip the elements with names in the excludedFruits array
return null; // You can use any value or component here
}
return (
<div key={fruit.name} className="fruit-item">
<p className="fruit-name">Name: {fruit.name}</p>
<p className="fruit-color">Color: {fruit.color}</p>
</div>
);
});
return (
<div className='container'>
<h3>React Js Skip Element of Array in .map() Function</h3>
{result}
<p> Skipped Element : {excludedFruits.join(',')}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Js Skip Element Of Array
Explanation of code
Let's consider a scenario where you have an array of fruits, and there are some fruits you want to exclude from the rendering process. The goal is to create a list of fruits with their names and colors while excluding specific fruits from the list. Here's a breakdown of the code snippet you provided
xxxxxxxxxx
const data = [
{ name: "Apple", color: "red" },
{ name: "Banana", color: "yellow" },
{ name: "Kiwi", color: "green" },
{ name: "Orange", color: "orange" },
{ name: "Grapes", color: "purple" },
];
const excludedFruits = ["Kiwi", "Grapes"];
In the code above, we have an array called data
containing various fruit objects, each with a name and color. Additionally, there's an array named excludedFruits
that holds the names of fruits we want to skip during rendering
Now, let's see how we can use the .map() function to create a list of fruits, excluding the ones specified in the excludedFruits
array:
xxxxxxxxxx
const result = data.map(fruit => {
if (excludedFruits.includes(fruit.name)) {
// Skip the elements with names in the excludedFruits array
return null; // You can use any value or component here
}
return (
<div key={fruit.name} className="fruit-item">
<p className="fruit-name">Name: {fruit.name}</p>
<p className="fruit-color">Color: {fruit.color}</p>
</div>
);
});
In the code above, we use the .map() function to iterate over the data
array. For each fruit object, we check if its name is in the excludedFruits
array. If it is, we return null
to skip the rendering of that fruit. If not, we render the fruit's name and color as a JSX component.
Finally, we render the result in the App
component:
xxxxxxxxxx
return (
<div className='container'>
<h3>React Js Skip Element of Array in .map() Function</h3>
{result}
<p> Skipped Element : {excludedFruits.join(',')}</p>
</div>
);