Reputation: 623
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
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
Reputation: 2943
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