Here is my array, i try to compare multiple ids with id which is in nestead array in react native
here is function to compare with multiple id with selected ids :
const [addedItems,setItems] = useState(props.addItemsToCart)
const [selectedItems, setSelectedItems] = useState([]);
//my selectd items is : ex [0,4]
useEffect(() => {
const addedInCart = ResturentData.filter(item => item.foodItem.some(item => addedItems.includes(item.id)))
setSelectedItems(addedInCart)
},[addedItems])
Here is my array,
export const ResturentData = [
{
title: 'foodResturants.recommended',
foodItem: [
{
id: 0,
image: resturantProduct7,
title: 'foodResturants.vegCheese',
rate: '4.5',
price: 25,
items: 1,
clickedItem: false,
quantity: 1,
},
{
id: 1,
image: resturantProduct4,
title: 'foodResturants.barbarescaPasta',
rate: '4.5',
price: 25,
items: 1,
clickedItem: false,
quantity: 1,
},
],
},
{
title: 'foodResturants.quickBites',
foodItem: [
{
id: 2,
image: resturantProduct6,
title: 'foodResturants.fries',
rate: '4.5',
price: 25,
items: 1,
clickedItem: false,
quantity: 1,
}
],
},
];
i try to compare multiple ids with id which is in nestead array in react native
here is function to compare with multiple id with selected ids :
But i got result is different items how to fix this thanks in advance!
2
Answers
You can achieve it in multiple ways. I will show you 2 common and standard methods for this:
1. Using descriptive logical method (This is more understandable but a little complex way)
2. Using array prototype provided by javascript library (Shortcut and simplest way)
In the 2nd method, we use the some() method twice: first to iterate through the RestaurantData array, and then to iterate through the foodItem arrays within each restaurant. If any of the foodItem arrays contains an object with a matching ID, the some() method will return true, indicating that the ID is present.
This 2nd approach is more concise and aligns with JavaScript’s functional programming paradigm. It also makes the code easier to read and understand.