Find index of the nearest larger number of a number The task:


  Given an array of numbers and an index i, return the index of the
  nearest larger number of the number at index i, where distance is
  measured in array indices.
  
  For example, given [4, 1, 3, 5, 6] and index 0, you should return 3.
  
  If two distances to larger numbers are the equal, then return any one
  of them. If the array at i doesn't have a nearest larger integer, then
  return null.
  
  Follow-up: If you can preprocess the array, can you do this in
  constant time?


My solution:

const nearestLargestNumber = (arr, idx1) =&gt; {
  const num = arr[idx1];
  let nearestLargest;
  const findIdxOfNearestLargest = (idxOfNearestLargest, item, idx2) =&gt; {
    if (item &gt; num &amp;&amp;
       (idxOfNearestLargest === null || nearestLargest &gt; item )) {
      nearestLargest = item;
      idxOfNearestLargest = idx2;
    }
    return idxOfNearestLargest;
  };

  return arr.reduce(findIdxOfNearestLargest, null);
};

console.log(nearestLargestNumber([4, 1, 3, 5, 6], 0));
EDIT: I mistook "nearest" to mean "numerically closest" but the problem asks for minimum distance from the index.  As the other answer points out, there are faster methods than visiting every element.

The answer to the followup question is "yes."

"Larger" is ambiguous: if you ask someone for a "large negative number" they probably don't answer "negative one."   Attribute this to sloppiness on the author's part, unless you've reason to suspect trickery.

I'm not a fan of these variable names: idx1 should be idx0, or i0 or initialIndex.  nearestLargest isn't the largest anything and nearestLarger would be more accurate.  num is a number, but so is everything else—maybe minimum or baseline or mustBeGreaterThan. nearestLargestNumber contains an index, not a number, while the number is held in nearestLargest.

I suggest one common prefix for your index variables and another prefix for value variables (though you don't really need more than one).

const nearestGreater = (arr, i0) =&gt; arr.reduce(  
        (iNearestGreater, val, i) =&gt; 
            ( val &gt; arr[i0] &amp;&amp; ( iNearestGreater===null || val &lt; arr[ iNearestGreater ] ) ) ? 
                i : iNearestGreater,
        null
    );