0

I come to have two different arrays. One containing only ids as integers (coming from a searchBox) and another one containing objects, like:

categories = [1, 2, 5, 8];

items = [
  { title: 'Hello', description: 'whatever you want to be a description', categoryId: 1 },
  { title: 'Hello', description: 'whatever you want to be a description', categoryId: 3 }
]

I've been looking for a way to remove any item in the second array if its categoryId is equal to anyvalue present in the categories array.

At first I tried to splice, loop into them (and thus created some kind of infinite loop), look for indexOf... either I did it badly or used the wrong method but for three days now, nothing is doing the job.

Is there any method in JS to return a new array like items.splice(every.categories) (well I know this one doesn't exist but who knows... anything similar in ES6 ?

kissu
  • 40,416
  • 14
  • 65
  • 133
Loth
  • 3
  • 1

1 Answers1

0

You could just use the filter method on the second array and check if the categoryId exists in the first array

const categories = [1, 2, 5, 8];
const items = [ {  title: 'Hello', description: 'whatever you want to be a description', categoryId: 1 }, {  title: 'Hello', description: 'whatever you want to be a description', categoryId: 3 } ]

const result = items.filter(item => !categories.find(cat => cat === item.categoryId))
Stevetro
  • 1,933
  • 3
  • 16
  • 29