- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implementing the Array.prototype.lastIndexOf() function in JavaScript
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
Advertisements