Adding a predicate to jQuery's .first() method
<p>Is it possible, without greatly impacting on the original source code, to extend the jQuery <code>.first()</code> method so that it can accept a predicate parameter? Fundamentally what I want it to do is something similar to LINQ's <a href="http://msdn.microsoft.com/en-us/library/bb535050.aspx" rel="nofollow"><code>.First()</code></a>, C# method. In JavaScript it would look something like this:</p>

<pre><code>function first(arr, predicate) {
    for (var i = 0; i &lt; arr.length; i++) {
        // return the first item fulfilling the predicate
        if (predicate.call(arr[i])) {
            return arr[i];
        }
    }
}

var myArray = [1, 3, 5],
    myPredicate = function() {
        return this &gt;= 2;
    };

var result = first(myArray, myPredicate); // should give '3'
</code></pre>

<p>I know it can easily be achieved with JavaScript; I'm just curious if it's possible to easily extend an existing method within jQuery.</p>

<h2>Solution used:</h2>

<pre><code>$.fn.firstOne = function(predicate) {
    // validate the predicate is a function
    if ($.isFunction(predicate)) {
        // iterate through each item, finding the first match
        for (var i = 0; i &lt; this.length; i++) {
            if (predicate.call(this.eq(i), i)) {
                return this.eq(i);
            }
        }
    }

    // maintain chainability
    return $();
};
</code></pre>
