title: JavaScript forEach with selector -- functional replacement for JavaScript if statement
body: <p>I wrote the following code recently:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function genBoard(width, height, numMines) {
    let mineField = _.shuffle(Array(numMines).fill('*').concat(Array(width*height - numMines).fill(0)));
    mineField.forEach((elem, pos) =&gt; {
      if (elem == '*') {
        let blastArea = [pos-width-1, pos-width, pos-width+1, pos-1, pos+1, pos+width-1, pos+width, pos+width+1];
        blastArea.filter(p =&gt; p&gt;=0 &amp;&amp; p&lt;width*height &amp;&amp; mineField[p] != '*').forEach(p =&gt; mineField[p] += 1);
      }
    });
    _.chunk(mineField, width).forEach(row =&gt; console.log(row.join('')));
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Note that I'm using <code>_.shuffle</code> and <code>_.chunk</code> from <a href="https://lodash.com/docs/4.17.4%20lodash" rel="nofollow noreferrer">lodash</a>.</p>
  
  <p>I'd like to do this in as functional a way as possible.  So I'd like the middle part to be more like this:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>mineField.forEachFiltered((elem, pos) =&gt; {
    let blastArea = [pos-width-1, pos-width, pos-width+1, pos-1, pos+1, pos+width-1, pos+width, pos+width+1];
    blastArea.filter(p =&gt; p&gt;=0 &amp;&amp; p&lt;width*height &amp;&amp; mineField[p] != '*').forEach(p =&gt; mineField[p] += 1);
    },
    elem =&gt; elem == '*'
  );</code></pre>
  </div>
  </div>
  </p>
  
  <p>In other words, the <code>forEachFiltered</code> takes two functions (instead of <code>forEach</code> taking one), where the second function is a selector, or you could call it a predicate.  If you examine the code you'll see that I can't conveniently use a combination of <code>forEach</code> and <code>filter</code> as I need to know my position in the original array.  I have tried googling but haven't found any notion of <code>forEachFiltered</code> anywhere, and also not in lodash.  Do I have to write that function or is there another way (or just use the <code>if</code> statement)?</p>
  
  <p>P.S.: Example output with values 10, 6, 24:</p>
  
  <pre><code>*2233222**
  32****3*6*
  312445*5**
  5322*4*5**
  ***22*35**
  432112*3*3
  </code></pre>
  
  <p>P.P.S.:  To ask my question in the simplest possible way, how do you do <code>["my", "array", "of", "whatever"].forEach(func, selector)</code> ?</p>