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 thefindOne,findAll,findOneAsync, andfindAllAsyncmethods to enable binary search.
Signature
binarySearch(
sorted: T[],
matcher: string | number,
keySelector: (item: T) => string | number,
caseInsensitive: boolean
): T | undefinedParameters
| Parameter | Type | Description |
|---|---|---|
sorted | T[] | Pre-sorted array to search. |
matcher | string | number | Value to search for. |
keySelector | (item: T) => string | number | Function to extract comparison key from items. |
caseInsensitive | boolean | Whether 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)
