[Easy] Implement findIndex function
March 6, 2024
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee
Question Prompt
Imagine you're tasked with developing a function that efficiently locates specific elements within arrays. This function, named findIndex
, should accept three key parameters:
array
: The array to be searched.predicate
: A testing function that determines whether an element matches the desired criteria.fromIndex
(optional): A starting index for the search, defaulting to 0 if not specified.
Your goal is to implement findIndex
so that it returns the index of the first element within array
that satisfies the predicate
function. If no matching element is found, it should return -1.
findIndex(array, predicate, [(fromIndex = 0)]);
findIndex([1, 13, 7, 54], (num: number) => num > 10)) // 1
findIndex([1, 13, 7, 54], (num: number) => num > 200)) // -1
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
To find the index, we can do the following
- First determine the accurate starting index for the search. If
fromIndex
is negative, adjust it by addingarray.length
. This is because the last item in an array is at index-1
and by that we can infer-1
is the same asarray.length - 1
. Thus, to adjust the negative index, we can do it by addingarray.length
. - Then loop through the array, starting from the
startIndex
. - For each element, call the
predicate
function, which acts as a "tester" to see if the element meets the specified criteria. - If the
predicate
function returnstrue
for an element, meaning a match is found, the function immediately returns that element's index within the array. - If the loop completes without finding any elements that satisfy the
predicate
, the function returns -1 to indicate that no match was found.
function findIndex(array, predicate, fromIndex = 0) {
const startIndex = fromIndex < 0 ? fromIndex + array.length : fromIndex;
for (let i = startIndex; i < array.length; i++) {
if (predicate(array[i])) {
return i;
}
}
return -1;
}