- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding reversed index of elements in arrays - JavaScript
We are required to write a JavaScript function that takes in an array of String/Number literals as the first argument and a String/Number as the second argument.
If the variable taken as the second argument is not present in the array, we should return -1.
Else if the number is present in the array, then we have to return the index of position the number would have occupied if the array were reversed. We have to do so without actually reversing the array.
Then at last we have to attach this function to the Array.prototype object.
For example −
[45, 74, 34, 32, 23, 65].reversedIndexOf(23); Should return 1, because if the array were reversed, 23 will occupy the first index.
Example
Following is the code −
const arr = [45, 74, 34, 32, 23, 65]; const num = 23; const reversedIndexOf = function(num){ const { length } = this; const ind = this.indexOf(num); if(ind === -1){ return -1; }; return length - ind - 1; }; Array.prototype.reversedIndexOf = reversedIndexOf; console.log(arr.reversedIndexOf(num));
Output
This will produce the following output in console −
1
- Related Articles
- Finding the sum of all common elements within arrays using JavaScript
- Finding the inclination of arrays in JavaScript
- Finding intersection of multiple arrays - JavaScript
- Finding median index of array in JavaScript
- Finding intersection of arrays of intervals in JavaScript
- Finding the continuity of two arrays in JavaScript
- Finding the intersection of arrays of strings - JavaScript
- Finding deviations in two Number arrays in JavaScript
- Finding intersection of arrays that contain repetitive entries in JavaScript
- Finding Common Item Between Arbitrary Number of Arrays in JavaScript
- Finding maximum number from two arrays in JavaScript
- Finding sum of all unique elements in JavaScript
- Finding quarter based on month index in JavaScript
- Finding matches in two elements JavaScript
- Finding the difference between two arrays - JavaScript

Advertisements