0

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;
    });
});

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Function find to accomplish that requirement? What about the function some?
Although will work, the best approach is using the function some.
2

Would using some work here?

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

6 Comments

You still need to return the result from .some
This is also less performant than find when you have a lot of items in your cart. If the item doesn't exist in the cart, this code will loop through every cartItem instead of stopping once it finds a match.
@ChaseDeAnda That's incorrect, Array#some tells you whether a single element matches it, so it will also stop after it finds it, and is the better one to use because in find, you are wasting its return value since we only need a boolean.
Right, they both work the same, but how they are using it here is missing out on the performance of using .some or .find.
@ChaseDeAnda the way was implemented that arrow function doesn't need a return statement.
|
0

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

1 Comment

So how should OP fix it? They want to know a solution to their problem, not just why it's not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.