I have below fruitData
const fruitData = [{ fruitname: 'apple', fruitprice: '200', fruitcolor: 'red'},
{ fruitname: 'mango', fruitprice: '500', fruitcolor: 'yellow'},
{ fruitname: 'berry', fruitprice: '300', fruitcolor: 'red'}];
In below return section, I am trying to check which fruits in fruitData have color ‘red’.
return (
<section>
{fruitData.map((info) => {
if (info.fruitcolor === ‘red’) {
// return filtered fruit data
return null;
}
Can you help me how I should return filtered fruit data. I want it to be in below format
const filteredfruitData = [{ fruitname: 'apple', fruitprice: '200', fruitcolor: 'red'},
{ fruitname: 'berry', fruitprice: '300', fruitcolor: 'red'}];
5
Answers
Use
filter
method to filter onred
colorYou should be using
filter
method in this scenario,Check demo
Here you go!
Hey you can try this using array method map to copy your data and showing the result.
You may avoid using adding any escaping logic while using
Array.map()
method. Instead, you may useArray.filter()
method beforeArray.map()
.