userNick
userNick

Reputation: 623

How to filter array based on items being in another array?

I have two arrays and I want to filter the second based on what's in the first.

const items = [{itemid: 1, itemname: "hello world"}, {itemid: 2, itemname: "test"}]
const links = [{source: 1, target 2}, {source: 3, target: 4}]

//desired output
filteredLinks = [{source: 1, target: 2}]

In this example, since {source: 3, target: 4} don't match any itemid values from items, I want that object to be filtered out in a new array filteredLinks. I thought I could do this by iterating through items and finding the matches that way, but it isn't returning anything.

let filteredLinks = links.filter((i) => 
                                   i.source.includes(
                                      items.forEach((x) => {
                                      return x.itemid;
                                   })
                                 ) || 
                                   i.target.includes(
                                      items.forEach((x) => {
                                      return x.itemid;
                                   })
                                 )
                              )

Is there any way to achieve this similar to what I'm trying?

Upvotes: 1

Views: 46

Answers (2)

MWO
MWO

Reputation: 2806

Unlike the other solution, this one checks for source and for target.

const items = [{
  itemid: 1,
  itemname: "hello world"
}, {
  itemid: 2,
  itemname: "test"
}]
const links = [{
  source: 1,
  target: 2
}, {
  source: 3,
  target: 4
}]

const ids = items.map(item => item.itemid);
const filteredLinks = links.filter((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    if (ids.includes(value)) {
      return obj;
    }
  }
})
console.log(filteredLinks)

Upvotes: 0

IvanD
IvanD

Reputation: 2943

  1. Create a list of IDs that are allowed
  2. Filter links for which id is in the list of allowed IDs

Also, you can do it without step 1, but then you will basically go through items over and over again, which is inefficient.

const items = [{
  itemid: 1,
  itemname: "hello world"
}, {
  itemid: 2,
  itemname: "test"
}]

const links = [{
  source: 1,
  target: 2
}, {
  source: 3,
  target: 4
}]

const ids = items.map(item => item.itemid); // will yield and array [1, 2]

const filteredLinks = links.filter(link => ids.includes(link.source))

console.log(filteredLinks)

Upvotes: 1

Related Questions