0

I have an array of objects that look 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}]
}
]

I am trying to filter objects from the above array using something similar to includes against an existing array which looks like the following:

let secondarray = ['Jaw', 'Taw']

How would I return a list of objects which has a tool named within the second array?

Thanks for your time!

2 Answers 2

1

You can use some() with the tools inside filter()

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'}]}]
let secondarray = ['Jaw', 'Taw']

let filtered = array.filter(item => item.tools.some(obj => secondarray.includes(obj.toolname)))

console.log(filtered)

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

1 Comment

This is exactly what I was looking for- nice and concise. Thank you!
1

I think you might use something like this:

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' }]
    }
]
let secondarray = ['Jaw', 'Taw']
let filteredArray = array.filter(ch => {
    let controlArray = ch.tools.map(t => t.toolname);
    return secondarray.some(t => controlArray.includes(t));
});
console.log(filteredArray);
/**
which returns 

[ { id: 1, name: 'Foo', tools: [ [Object], [Object] ] },
  { id: 3, name: 'Loo', tools: [ [Object], [Object] ] } ]

*/

1 Comment

This is a great method as well- thank you very much!!

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.