How to implement Array.prototype.findIndex? JavaScript Interview Question | Problem Solving | JavaScript Polyfills
In this question, the candidate needs to implement a function customFindIndex
that mimics the behaviour of Array.prototype.findIndex
method.
More about Array.prototype.findIndex
The findIndex()
method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
Examples
const array = [1,2,3,12,13,15];
const greaterThanTen = (element) => element > 10;
console.print(array.findIndex(greaterThanTen));
// expected output: 3
Syntax
The customFindIndex
takes two parameters
callback
function
Function to execute on each value in the array. The function is called with the following arguments:
element
- The current element in the array.
index
- The index (position) of the current element in the array.
array
- The array that
customFind
was called on.
The callback must return a truthy value to indicate a matching element has been found.
thisArg
(Optional)
Object to use as this
inside callbackFn.
customFindIndex(callback, thisArg)
Submission
Start the timer, complete your solution, and test it against the test cases provided by the platform. Ideally, you should finish this question within 15 mins. Share your solution with us -- https://twitter.com/devtoolstech