FairyQueen
FairyQueen

Reputation: 2373

How to filter an array with another array in React Native?

So I am basically trying to say "give me all added items that were not actually added to the cart" with my filter function below. If any of the addedItems product ids cannot be found in the cartItems ids then it should return those items. But instead unaddedCartItems is an empty array when I know there are addedItems ids that are not the same as any of the cartItems ids. Do anyone know how to achieve this?

const unaddedCartItems = addedItems.filter((addedItem) => {
    cartItems.forEach((cartItem) => {
        return cartItem.id !== addedItem.productId;
    });
});

Upvotes: 0

Views: 3829

Answers (3)

Chase DeAnda
Chase DeAnda

Reputation: 16441

It's because your return is nested under forEach and you aren't returning that value in your filter. Instead, use find:

const unaddedCartItems = addedItems.filter( addedItem => {
    return !cartItems.find( cartItem => cartItem.id === addedItem.productId );
});

find loops through an array until it finds a matching item. This means that if it finds the id in cartItems, it will immediately stop the loop and return the item.

Upvotes: 3

Ashraf Samir
Ashraf Samir

Reputation: 9

because your return is nested under forEach and you aren't returning that value in your filter

Upvotes: 0

emjrose
emjrose

Reputation: 112

Would using some work here?

const unaddedCartItems = addedItems.filter((addedItem) => 
    !cartItems.some(cartItem => cartItem.id === addedItem.productId);

Upvotes: 2

Related Questions