DEV Community

Cover image for HasAllChildren
sndp
sndp

Posted on

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.

Discussion (0)