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;
}
};
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))
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With