TrueIfAll and TrueIfAny Functions for Javascript Arrays

I’m primarily a .NET programmer and therefore, I’ve become very familiar with LINQ.  I recently needed a trueIfAny function on a few javascript arrays, much like the All<> and Any<> functions in LINQ.   I am aware of LINQ to Javascript which does implement those functions, but I just needed something simple.

Fortunately, it’s very easy to extend functionality of objects thanks to prototype.  Here is the code I wrote to accomplish the task of creating a trueIfAll and trueIfAny function:

if (Array.prototype.trueIfAny == null) {
    Array.prototype.trueIfAny = function (conditionCheck) {
        for (var i = 0; i < this.length; i++) {
            if (conditionCheck(this[i])) {
                return true;
            }
        }
        return false;
    }
}

if (Array.prototype.trueIfAll == null) {
    Array.prototype.trueIfAll = function (conditionCheck) {
        for (var i = 0; i < this.length; i++) {
            if (!conditionCheck(this[i])) {
                return false;
            }
        }
        return true;
    }
}

And to use it:

if(myArr.trueIfAny(function(ele) { return ele.Toggle; }))
{
//Run if any records are true
}

if(myArr.trueIfAll(function(ele) { return ele.Toggle; }))
{
//Run if all records are true
}

The trueIfAll and trueIfAny functions iterate through the array, calling the passed in function (conditionCheck) each time. The passed in function accepts one parameter and needs to return boolean. The parameter is the element produced by the iteration.

In the case of trueIfAll, if the passed in function ever returns false, trueIfAll will return false. In the case of trueIfAny, if the passed in function ever returns true even once, trueIfAny returns true.

Hope this helps someone!

Be Sociable, Share!