Finding reversed index of elements in arrays - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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


raja
Published on 30-Sep-2020 13:36:40
Advertisements