Reputation: 309
I have an array of objects similar to the following:
let array = [
{
id: 1,
name: Foo,
tools: [{id:3, toolname: Jaw},{id:1, toolname: Law}]
},
{
id: 2,
name: Boo,
tools: [{id:2, toolname: Caw}]
},
{
id: 3,
name: Loo,
tools: [{id:3, toolname: Jaw}, {id:4, toolname: Maw}, {id:6, toolname: Taw}]
}
]
I have a second array that looks like the following:
let secondarray = ['Jaw', 'Taw']
How can I return a list of objects that include only BOTH of the items in the second array? So if an object only has one of the two, the object would not be included. In addition, if the object contains other tools
not in the secondarray
, but includes both items in the secondarray
, it should still be included.
Thus the expected output of this filter would be:
{
id: 3,
name: Loo,
tools: [{id:3, toolname: Jaw}, {id:4, toolname: Maw}, {id:6, toolname: Taw}]
}
Thank you for your time!
Upvotes: 1
Views: 43
Reputation: 386600
You could iterate the data array and then check if all of the reqired tools are in the actual object.
let array = [{ id: 1, name: 'Foo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }] }, { id: 2, name: 'Boo', tools: [{ id: 2, toolname: 'Caw' }] }, { id: 3, name: 'Loo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }, { id: 6, toolname: 'Taw' }] }],
required = ['Jaw', 'Taw'],
result = array.filter(({ tools }) =>
required.every(v => tools.some(({ toolname }) => toolname === v))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another approach to omit the loop over tools
more than once by using a Set
.
let array = [{ id: 1, name: 'Foo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }] }, { id: 2, name: 'Boo', tools: [{ id: 2, toolname: 'Caw' }] }, { id: 3, name: 'Loo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }, { id: 6, toolname: 'Taw' }] }],
required = ['Jaw', 'Taw'],
result = array.filter(({ tools }) =>
required.every(
Set.prototype.has,
new Set(tools.map(({ toolname }) => toolname))
)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2