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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay