title: Find previous or next number in array from a given number
body: <p>I have a requirement whereby I need to find the previous or next number in an array from a given number. I've seen the following example which returns the closest number from a given number.</p>
  
  <pre><code>var values = [0, 7, 10, 17];
  var givenNumber = 5;
  var closest = values.reduce(function (previous, current) {
    return (Math.abs(current - givenNumber) &lt; Math.abs(previous - givenNumber) ? current : previous);
  });
  console.log(closest); // outputs 7
  </code></pre>
  
  <p>How do I go about returning the previous or next number closest to the given number? For example</p>
  
  <ul>
  <li>If givenNumber = 5, then closest previous number would be 0</li>
  <li><p>If givenNumber = 5, then closest next number would be 7</p></li>
  <li><p>If givenNumber = 8, then closest previous number would be 7</p></li>
  <li><p>If givenNumber = 8, then closest next number would be 10</p></li>
  <li><p>If givenNumber = 15, then closest previous number would be 10</p></li>
  <li><p>If givenNumber = 15, then closest next number would be 17</p></li>
  <li><p>If givenNumber = 20, then closest previous number would be 17</p></li>
  <li>If givenNumber = 20, then closest next number would be 0</li>
  </ul>
  
  <p>For more information about the <strong>reduce</strong> function please see the following</p>
  
  <ul>
  <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce</a></li>
  <li><a href="https://msdn.microsoft.com/library/ff679975%28v=vs.94%29.aspx" rel="nofollow">https://msdn.microsoft.com/library/ff679975%28v=vs.94%29.aspx</a></li>
  <li><a href="http://www.tutorialspoint.com/javascript/array_reduce.htm" rel="nofollow">http://www.tutorialspoint.com/javascript/array_reduce.htm</a></li>
  </ul>