DEV Community

Cover image for HasAllChildren
sndp
sndp

Posted on

6 2

HasAllChildren

The below is a function to check if an sub array consist of all the elements of a given array.

const hasChild = (array, child) => {
    const ruleA = array !== undefined;
    const ruleB = child !== undefined;
    const ruleC = array.find(c => c === child) === child;
    return ruleA && ruleB && ruleC;
}

const hasAllChildren = (array, subArray) => {
    const ruleA = array !== undefined;
    const ruleB = subArray !== undefined;
    const ruleC = subArray
        .filter(c => hasChild(array, c))
        .length === array.length;
    return ruleA && ruleB && ruleC;
}
Enter fullscreen mode Exit fullscreen mode

Now, What this function hasAllChildren(array, subArray) does when called is checking if all items match to be available in the array.

Notice - This method does not check if these passed arrays are equal. It simply checks if the elements are available.

First it checks all the arguments passed to our method are defined.

  1. array (original array)
  2. subArray (comparing array)

For each element we need to check if element is available in the array. We need hasChild(array, child) to do this. It finds the element in the array and returns true if found. For all subArray elements it needs to return true;

The reason to check if undefined is that if not it returns true.

If all elements contains we can say that count of all checked available items is equal to the original array's size.

Finally we return if all rules and checks passed by returning
ruleA * ruleB * ruleC.

Thank for reading.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay