0

I have an array of available items:

const items = [{id: 1, title: Item 1}, {id: 2, title: Item 2}, {id: 3, title: Item 3}]

and an array of items that my user has purchased:

const purchasedItems = [{id: 1, title: Item 1}, {id: 2, title: Item 2}]

I want to display an array of items that are still available to them to purchase that they haven't bought yet, i.e. just item 3 in this case. So I want an array returned with just Item 3 in it.

I have tried:

const availableItems = items.filter(
    (item) => !purchasedItems.includes(item)
  )

However this just returns a list of all the items again.

Think I must be missing something quite obvious, any help appreciated!

2
  • change .includes() to .findIndex() and use a callback Commented Mar 28, 2022 at 9:12
  • Please try this: const remainingItems = items.filter(({ id }) => (!(purchasedItems.some(x => x.id === id))));. It uses .filter to pick id from items array and retain only those which do not have a corresponding element in purchasedItems array. Commented Mar 28, 2022 at 9:15

2 Answers 2

2

includes won't work here because it will only compare the items with a strict equality (as in item1 === item2). It will only works if your items are the same objects with the same reference.

A little example:

const obj1 = { test: 1 };
const obj2 = obj1;
const obj3 = { test: 1 };

console.log(obj1 === obj2); // true
console.log(obj1 === obj3); // false

So, in your case, you have to do a more complex work in your filter function:

const availableItems = items.filter(item1 => !purchasedItems.some(item2 => item1.id === item2.id));
Sign up to request clarification or add additional context in comments.

Comments

-1

Use findIndex() instead of includes

const items = [{ id: 1, title: 'Item 1' }, { id: 2, title: 'Item 2' }, { id: 3, title: 'Item 3' }]

const purchasedItems = [{ id: 1, title: 'Item 1' }, { id: 2, title: 'Item 2' }]

const availableItems = items.filter((item) => (purchasedItems.findIndex(purchasedItem => purchasedItem.id === item.id) == -1))

console.log(availableItems)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.