find

find(iterator) -> firstElement | undefined

Finds the first element for which the iterator returns true. Convenience alias for detect, but constitutes the preferred (more readable) syntax.

This is the short-circuit version of the full-search findAll. It just returns the first element that matches your predicate, or undefined if no element matches.

Examples


// An optimal exact prime detection method, slightly compacted.
function isPrime(n) {
  if (2 > n) return false;
  if (0 == n % 2) return (2 == n);
  for (var index = 3; n / index > index; index += 2)
    if (0 == n % index) return false;
  return true;
} // isPrime

$R(10,15).find(isPrime)
// -> 11

[ 'hello', 'world', 'this', 'is', 'nice'].find(function(s) {
  return s.length = 3;
})
// -> 'is'