Implementing the Array.prototype.lastIndexOf() function in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The lastIndexOf() function in JS returns the index of the very last occurrence of the element, passed into it as an argument, in the array, if it exists. If it does not exist the function returns -1.

For example −

[3, 5, 3, 6, 6, 7, 4, 3, 2, 1].lastIndexOf(3) would return 7.

We are required to write a JavaScript function that have the same utility as the existing lastIndexOf() function.

And then we have to override the default lastIndexOf() function with the function we just created. We will simply iterate from the back until we find the element and return its index.

If we do not find the element, we return -1.

Example

Following is the code −

const arr = [3, 5, 3, 6, 6, 7, 4, 3, 2, 1];
Array.prototype.lastIndexOf = function(el){
   for(let i = this.length - 1; i >= 0; i--){
      if(this[i] !== el){
         continue;
      };
      return i;
   };
   return -1;
};
console.log(arr.lastIndexOf(3));

Output

This will produce the following output in console −

7
raja
Published on 18-Sep-2020 13:32:11
Advertisements