JavaScript indexOf() and lastIndexOf(): Find Indexes Fast
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
indexOf() and lastIndexOf() search arrays and strings for a value and return its position. indexOf(value, fromIndex) scans forward from the beginning (or from fromIndex) and returns the first matching index. lastIndexOf(value, fromIndex) scans backward from the end (or from fromIndex) and returns the last matching index. If no match exists, both methods return -1. For arrays, matching uses strict equality (===), so object values must reference the same object. For strings, matching is case-sensitive and accepts substrings. Inputs are the search value and an optional numeric starting index; outputs are zero-based indexes or -1. The examples show duplicates, optional start positions, missing values, string searches, and a helper that collects every occurrence by repeatedly calling indexOf() with an incremented start position. Time complexity is O(n) in the worst case for both methods because they may scan the entire array or string. The optional fromIndex can reduce the scanned range, but the worst-case complexity remains linear. Use these methods when you need the first or last position rather than a boolean result.