es-stl - v3.0.2
    Preparing search index...
    • Finds the index of an item whose projected numeric value equals searchValue.

      Type Parameters

      • T

        Element type stored in the array.

      Parameters

      • array: T[]

        Sorted array to search.

      • searchValue: number

        Numeric value to match.

      • callback: SearchCallback<T>

        Projects each element to its comparable numeric value.

      Returns number

      The matching index, or -1 when no element matches.

      The input array must already be sorted in ascending order by the numeric value returned from callback. If multiple elements project to the same value, any matching index may be returned.

      const values = [{ id: 1 }, { id: 3 }, { id: 5 }];
      const index = binarySearch(values, 3, (value) => value.id);
      // index === 1
      binarySearch([2, 4, 8, 16], 8, (value) => value);
      // => 2
      binarySearch([10, 20, 30], 25, (value) => value);
      // => -1