Home
bricks

count and deepCopy

Here a a couple more methods for JavaScript Array Objects.

count takes a test function as an argument. It counts the number of elements in the array recursively, that pass the test function.

deepCopy returns a copy of the complete array structure with each sub array recursively copied.

Array.prototype.count = function(testFunction) {
    var count = 0;
    for(var i = 0; i < this.length; i++) {
        if (this[i].constructor == Array) {
            count += this[i].count(testFunction);
        } else {
            if (testFunction) {
                if (testFunction(this[i])) {
                    count += 1;
                }
            } else {
                count += 1;
            }
        }
    }
    return count;
}

Array.prototype.deepCopy = function() {
    var buffer = [];
    for(var i = 0; i < this.length; i++) {
        if (this[i].constructor == Array) {
            buffer.push(this[i].deepCopy());
        } else {
            buffer.push(this[i]);
        }
    }
    return buffer;
}

For example:

[1,2,3,[4,5,6,[7,8],9]].count(function(v) { return v > 5 });

Returns 4