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!

Jordan1993
  • 864
  • 1
  • 10
  • 28
  • change `.includes()` to `.findIndex()` and use a callback – Salman A Mar 28 '22 at 09: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. – jsN00b Mar 28 '22 at 09:15

2 Answers2

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));
Magus
  • 14,796
  • 3
  • 36
  • 51
-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)
Sahil Thummar
  • 1,926
  • 16
  • 16