Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an array and predicate, find the first matching element

Is there an existing function that finds the first array element that matches some general predicate?

$.fn.findFirstMatching = function(predicate) {
    var result;
    $.each(this, function(index, value) {
        if (predicate(index, value)) {
            result = {index: index, value: value};
        }
    });
    if (result) {
        return result;
    }
};
like image 961
ripper234 Avatar asked Jul 05 '12 12:07

ripper234


2 Answers

As of ES2015, you can use Array.prototype.find

An example of using it looks like this:

// outputs the first odd number
console.log([2,4,10,5,7,20].find(x => x%2))
like image 200
Allain Lalonde Avatar answered Oct 16 '22 00:10

Allain Lalonde


Another solution would be:

$.grep(yourArray, function (value, index) { return value == 42 } )[0]

Note that the order of the arguments should be value, index

Docs for jQuery.grep.

Of course, using _underscore is much more elegant and efficient (as $.grep applies the predicate on the all items of the array, it doesn't stop after the first match), but anyway :)

like image 29
turdus-merula Avatar answered Oct 16 '22 00:10

turdus-merula