title: JavaScript function to find the first result in an array
body: <p>I am looking for a functional way to find the first result in an array.</p>
  
  <pre><code>let result;
  for (let i = 0; i &lt; array.length; i++) {
    result = functionThatCalulatesResult(array[i]);
    if (result) {
      break;
    }
  }
  </code></pre>
  
  <p>Is the imperative way.</p>
  
  <pre><code>const item = array.find(i =&gt; functionThatCalulatesResult(i));
  </code></pre>
  
  <p>But now I have to calculate the result again.</p>
  
  <pre><code>const result = array.reduce(
    (result, item) =&gt; result ? result : functionThatCalulatesResult(i), 
    undefined
  );
  </code></pre>
  
  <p>But the reduce keeps going over all the items that don't need to be iterated.</p>
  
  <p>I am looking for something like</p>
  
  <pre><code>const result = firstResult(array, i =&gt; functionThatCalulatesResult(i));
  </code></pre>
  
  <p>That returns the first truthy result for the function without iterating the items past the first result.</p>
  
  <p>Most efficient thing I can think of is</p>
  
  <pre><code>const firstResult = (array, func) =&gt; {
    let result;
    array.some(i =&gt; result = func(i));
    return result;
  }
  </code></pre>
  
  <p>But it is not purely functional with the mutating of result.</p>
  
  <p>Edit:</p>
  
  <p>For people asking what is in the array I am trying to find the most efficient way of finding the parameter that returns a sort direction in this function.</p>
  
  <p><a href="https://stackblitz.com/edit/typescript-syhjq4" rel="nofollow noreferrer">https://stackblitz.com/edit/typescript-syhjq4</a></p>
  
  <p>I was using a reduce but have switched to a some with a mutation as the sort function mutates the array anyway.</p>