select and selectMany for Javascript Arrays

I’m a huge javascript fan.  My favorite language by far.  Easy to bolt on new functionality.  In most cases, using already-established libraries like the ever-awesome underscore library suffices.  For example, their collection-related functions are phat-ass!  Occasionally it’s nice to add functionality that boosts productivity.  Here’s a potential couple of them:

Array.prototype.select = Array.prototype.select || function (projector) {
    var result = [];
    for (var i = 0; i < this.length; i++) {
        result.push(projector(this[i]));
    }
    return result;
};

Array.prototype.selectMany = Array.prototype.selectMany || function (projector) {
    var result = [];
    for (var i = 0; i < this.length; i++) {
        result.addRange(projector(this[i]));
    }
    return result;
};

 

Combining a few other handy routines (like addRange and Where) to array, here’s a simple bin that shows selectMany in action.

1 thought on “select and selectMany for Javascript Arrays

Leave a comment