It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:


Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.
Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.


Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.

Both solutions above don't support offset searching either, so I've decided to write this:

(function(ns) {
  ns.search = function(array, callback, offset) {
    var size = array.length;

    offset = offset || 0;
    if (offset &gt;= size || offset &lt;= -size) {
      return -1;
    } else if (offset &lt; 0) {
      offset = size - offset;
    }

    while (offset &lt; size) {
      if (callback(array[offset], offset, array)) {
        return offset;
      }
      ++offset;
    }
    return -1;
  };
}(this));

search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3


How to find first element of array matching a boolean condition in JavaScript?
In the following graph I would like to obtain the point B:



According to the author this B is equal to:



The question that I have is how the author obtain that result. It says that in A is a point x_(i), so I suppose that he projects A onto the unit vector w; and because B can be any point on the hyperplane he uses Euclidean distance to perform its calculations; something like:

B=A-dist(A,B)

B=x_(i)-Y_(i).w/||w||


Is that ok? but I am not quite sure why he multiply the value of Y_(i) with the unit vector, why is that?

Thanks
