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