Toolbox-XToolbox-X

Binary Search

Performs a binary search on a sorted array using a custom key selector function.

binarySearch()

Performs a binary search on a sorted array using a custom key selector function.

Important Note

  • You should not use this method explicitly unless you have a specific use case that requires it.
  • Instead, consider using the { forceBinary: true } option in the findOne, findAll, findOneAsync, and findAllAsync methods to enable binary search.

Signature

binarySearch(
  sorted: T[],
  matcher: string | number,
  keySelector: (item: T) => string | number,
  caseInsensitive: boolean
): T | undefined

Parameters

ParameterTypeDescription
sortedT[]Pre-sorted array to search.
matcherstring | numberValue to search for.
keySelector(item: T) => string | numberFunction to extract comparison key from items.
caseInsensitivebooleanWhether to ignore case for string comparisons.

Returns

T | undefined — First matching item found, or undefined if not found.

Description

This method implements a binary search algorithm with the following characteristics:

  • Works on pre-sorted arrays.
  • Supports both string and numeric keys.
  • Optional case-insensitive string comparison.
  • Returns the first match found.
  • O(log n) time complexity.

Example Usage

playground.ts

Performance

  • Time Complexity: O(log n)
  • Space Complexity: O(1)

Use Cases

  • Searching large sorted datasets.
  • Implementing fast lookup for static data.
  • Optimizing search performance for read-heavy applications.

Last updated: Sun, Jul 19, 2026 09:00:11AM (UTC)

On this page