The indexOf() method returns the first index at which a given element can be found, or -1 if not present.
β Implementation
Array.prototype.customIndexOf = function(searchElement, fromIndex = 0) { // Normalize negative fromIndex to count from the end of the array if (fromIndex < 0) { fromIndex = Math.max(this.length + fromIndex, 0); // Adjust negative index } // Iterate through the array starting from fromIndex for (let i = fromIndex; i < this.length; i++) { if (this[i] === searchElement) { return i; // Return the index of the first match } } return -1; // Return -1 if the element is not found }; // Example usage: const array = [2, 9, 9]; console.log(array.customIndexOf(2)); // Output: 0 console.log(array.customIndexOf(7)); // Output: -1 console.log(array.customIndexOf(9, 2)); // Output: 2 console.log(array.customIndexOf(2, -1)); // Output: -1 console.log(array.customIndexOf(2, -3)); // Output: 0
How It Works:
- Negative
fromIndex: IffromIndexis negative, it is adjusted to count from the end of the array. For example,fromIndex = -1starts the search from the last element. - Array Iteration :
The loop starts from the
fromIndex(or0if not provided) and compares each element withsearchElementusing strict equality (===). - Return Index or -1 :
- If
searchElementis found, the method returns the index of the first match. - If no match is found, it returns
-1.
Example Walkthrough:
customIndexOf(2): Starts at index0and finds2at index0, so it returns0.customIndexOf(7): No match is found, so it returns-1.customIndexOf(9, 2): Starts at index2and finds9at index2, so it returns2.customIndexOf(2, -1): Starts searching from the last element (index 2), doesn't find2, so it returns-1.customIndexOf(2, -3): Starts searching fromindex 0, finds2at index0, so it returns0.
This implementation mimics Array.prototype.indexOf, with additional support for negative fromIndex, ensuring the search works as expected.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `[2, 9, 9].customIndexOf(9)` return?
Q2What comparison does `indexOf()` use to find elements?
Q3What does `[1, 2, 3].customIndexOf(1, 1)` return?