Javascript’s Filter on an Array of Objects

Are you trying to use Javascript’s filter on an array of objects that contain arrays? Are you having trouble getting it to return elements to conditionally rebuild that array? I had the same issue and blamed the filter method for a quick sec. Buuuut lo and behold it was me as always.

Still new to JS and struggling with the fundamentals? Check out Javascript: The Defenitive Guide (paid link) to brush up.

My Setup

Recreating the Problem

So, I had something kind of like the following. My case was a bit more nested but the following array should work. I Googled all sorts of variations of “filter method with nested forloops” but it didn’t return much. I was treading on new territory or so I thought.

myArray = [{test:'test', array: [{check:true}, {check: true}]},
{test:'test', array: [{check:false}, {check: true}]},
{test:'test', array: [{check:true}, {check: true}]}]

I then wanted to filter out any object that had at least one check parameter set to false. I was looking to be left with the first and third element of the array I defined above. I initially did something like this:

myArray.filter(element => {
    const subArray = (element || [{}]).array||[{}]
    subArray.forEach(chunk => {
        const temp = (chunk || {}).check
        if(temp){return true}
        else{return false}
    })
})

Solution to the Broken Filter

So, the problem with our use of Javascript’s filter on an array of objects lies with returning inside of the forEach statement. We could instead create a temporary array that holds the statuses of what we want to check and once the forEach is done decide whether or not we want the element returned.

myArray.filter(element => {
    let subArray = (element || [{}]).array||[{}]
    let statusArray = []
    subArray.forEach(chunk => {
        const temp = (chunk || {}).check
        statusArray.push(temp)
    })
    return !statusArray.includes(false)
})

This should work but it’s still kind of ugly. I later discovered JS’s “some” method which breaks prior to finishing its looping. So the grander problem was the forEach method which loops through every record regardless if you return. The some method would have allowed us to potentially avoid creating that statusArray. I haven’t tested it out at all, but it might be a good lead.

Conclusion

The forEach method doesn’t break even if you return!!! Happy coding! Check out this article if you’re still thirsty for knowledge. Feel free to reach out or comment if I misspoke or you have any advice. Any and all feedback is greatly appreciated!

Leave a Comment