0
Hours
0
Minutes
0
Seconds
You need Login/Signup to run/submit the code.

How to implement Array.prototype.lastIndexOf? JavaScript Interview Question | Problem Solving | JavaScript Polyfills

@Yomesh Gupta
762

In this question, the candidate needs to implement a function customLastIndexOf that mimics the behaviour of Array.prototype.lastIndexOf method.

More about Array.prototype.lastIndexOf

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex. -1 is returned.

Examples

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// expected output: 1

console.log(animals.lastIndexOf('Dodo', 2));
// expected output: 0

Syntax

The customLastIndexOf takes two parameters

  1. searchElement

Element to locate in the array.

  1. fromIndex (Optional)

The position in the array at which to start searching backwards. Defaults to the array's length minus one (arr.length - 1), causing the whole array to be searched.

A fromIndex value greater than or equal to the length of the array also causes the whole array to be searched.

A fromIndex value greater than 0 is taken as the offset from the beginning of the array.

A fromIndex value less than 0 is taken as the offset from the end of the array — in other words, it is taken as specifying the position at array.length + fromIndex. Therefore, if array.length + fromIndex is less than 0, the array is not searched, and the method returns -1.

customLastIndexOf(searchElement, fromIndex?)

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 30 mins. Share your solution with us -- https://twitter.com/devtoolstech

Loading IDE...