1

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!

1 Answer 1

2

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; }

Sign up to request clarification or add additional context in comments.

1 Comment

This worked flawlessly. Thanks so much for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.