Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Removing elements that appear in one array from another array

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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));
about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!